如何从基本通用摘要 class 中获取只读字段值

How to get readonly field value from base generic abstract class

我想从基本通用摘要 class Base<A, B> 中检索只读字段值 _classC .

我试过的

FieldInfo.GetValue肯定是用的,但是我猜不出正确的参数。

认为派生的实例 class 没问题。

var derived = new Derived();
var baseType = typeof(Base<,>);

var classCField = baseType
  .GetField("_classC", BindingFlags.NonPublic 
    | BindingFlags.Static 
    | BindingFlags.Instance 
    | BindingFlags.FlattenHierarchy);

classCField.GetValue(derived);

我得到的错误

InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.

这可能吗?

类型定义

public interface IBase<A, B>
    where A : class
    where B : class, new()
{
    
}

public class ClassD
{
    
}

public class ClassC
{
    
}

public abstract class Base<A, B> : IBase<A, B>
    where A : class
    where B : class, new()
    {
        private readonly ClassC _classC = new ClassC();
    }

public class Derived : Base<ClassC, ClassD>
{
}

这样做:

var field = typeof(Derived).BaseType.GetField("_classC", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
var value = field.GetValue(derived);

您的第一个错误是由于使用开放泛型类型引起的,您需要一个构造的泛型类型(例如 Base<ClassC, ClassD>)。下一个错误是您的字段不是静态的。

至于重现:它是 DotNetFiddle,它以关于反射的过时信任模型运行。在 IdeOne 这运行得很好:

public class Test
{
    public static void Main()
    {
        var derived = new Derived();
        var baseType = derived.GetType().BaseType;
        
        var classCField = baseType.GetField("_classC", BindingFlags.NonPublic | BindingFlags.Instance);
                
        Console.WriteLine(classCField.GetValue((Base)derived));
    }
}

public class ClassC
{
}

public abstract class Base//<A, B> : IBase<A, B> where A : class where B : class, new()
{
    private readonly ClassC _classC = new ClassC();
}

public class Derived : Base//<ClassC, ClassD>
{
}