So I have this object with multiple levels of subclasses, like so (not actual object but an abstraction to convey it’s structure):
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;
}
}
I’ve tried to extract the fields of TypeA and it’s subclasses (SubTypeA and SubTypeB) like so:
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));
}
}
But I get this exception:
ArgumentException: Field 'Field1' defined on type 'SubTypeA' is not a field on the target object which is of type 'MonoType'.
Printing the FieldType for t yields the expected result ‘SubTypeA’ etc.
Am I doing something wrong?
Yes – in this expression:
The parameter passed to
GetValueshould be an instance of the type that defines the field. It should be the object that contains the particular field value you want to get.t.FieldTypeis an instance of the typeSystem.Type