简体   繁体   中英

Get FieldInfo of inherited class

In C# I have classes which are derived in the following way:

MyClass1 <- MyClass2 <- MyClass3 <- MyClass4 (The 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM