所以我有这个具有多个子类级别的对象,就像这样(不是实际的对象,而是传达它的结构的抽象):
public class MasterType
{
public TypeA typeA = new TypeA();
public TypeB typeB = new TypeB();
public class TypeA
{
public SubTypeA subTypeA = new SubTypeA();
public SubTypeB subTypeB = new SubTypeB();
public class SubTypeA
{
public int Field1 = 10;
}
public class SubTypeB
{
public int Field2 = 20;
}
}
public class typeB
{
public int Field3 = 30;
}
}
我试图提取 TypeA 的字段及其子类(SubTypeA 和 SubTypeB),如下所示:
foreach (var t in MasterType.TypeA.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy))
{
foreach (var field in t.FieldType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
Console.WriteLine(field.Name + " | " + field.GetValue(t.FieldType));
}
}
但我得到了这个例外:
ArgumentException: Field 'Field1' defined on type 'SubTypeA' is not a field on the target object which is of type 'MonoType'.
打印 t 的 FieldType 会产生预期的结果“SubTypeA”等。
我做错了吗?