获取继承类的FieldInfo

时间:2010-10-08 07:27:53

标签: c# reflection

在C#中,我有以下列方式派生的类:

MyClass1 <- MyClass2 <- MyClass3 <- MyClass4 (The root class is MyClass1)

现在我有一个MyClass4 myClass4的实例。如何获取在MyClass2中声明的私有字段信息?我可以做到以下几点:

FieldInfo[] fields = model.GetType().BaseType.BaseType.
                       GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo fld in field)
{
    ....
}

如果继承级别未知会怎样?

1 个答案:

答案 0 :(得分:1)

你知道你在寻找MyClass2中的字段吗?如果是这样,请继续阅读CurrentType.BaseType,直至CurrentType == typeof(MyClass2)

IOW

Type lCurrentType = model.GetType();
while (lCurrentType != typeof(MyClass2) && lCurrentType != null)
{
    lCurrentType = lCurrentType.BaseType;
}
相关问题