开发者

Get FieldInfo of inherited class

开发者 https://www.devze.com 2023-01-19 00:31 出处:网络
In C# I have classes which are derived in the following way: MyClass1 <- MyClass2 <- MyClass3 <- MyClass4 (T开发者_运维百科he root class is MyClass1)

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消