In C# I have classes which are derived in the following way:
MyClass1 <- MyClass2 <- MyClass3 <- MyClass4 (T开发者_运维百科he root class is MyClass1)
Now I have an instance of MyClass4 myClass4. How to get a private field info declared in MyClass2? I can do the following:
FieldInfo[] fields = model.GetType().BaseType.BaseType.
GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo fld in field)
{
....
}
What if the inheritance level is unknown?
Do you know you are looking for a field in MyClass2
? If so, keep reading CurrentType.BaseType
until CurrentType == typeof(MyClass2)
.
Iow
Type lCurrentType = model.GetType();
while (lCurrentType != typeof(MyClass2) && lCurrentType != null)
{
lCurrentType = lCurrentType.BaseType;
}
精彩评论