2014-02-17 32 views
0

如何在.NET 4中使用反射来从派生类中获取基类的字段信息?GetField const类型的基类

例如,

class Parent 
{ 
    public const bool ParentField = true; 
} 

class Child : Parent 
{ 
    public const bool ChildField = true; 
} 

使用这些类:

Console.WriteLine(p.GetType().GetField("ParentField")); 
Console.WriteLine(c.GetType().GetField("ChildField")); 
Console.WriteLine(c.GetType().GetField("ParentField")); 

第三行不工作,我所期望的方式。 GetField从基类型获取字段时返回null。我试过了GetField的超负荷值和我能想到的所有不同的BindingsFlags值,但它总是返回null。

编辑

我应该已经清楚,这

c.GetType().GetField("ParentField",BindingFlags.FlattenHierarchy) 

也返回null。

回答

3

为了让你成为一个更具体一点与你结合的标志继承的常数:

c.GetType().GetField("ParentField", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy) 
+0

@hmqcnoesy它的工作原理在我的机器上[这里](http://dotnetfiddle.net/8Vp3Vg) ...什么是您的完整测试代码? – Vache

+0

哎呀抱歉!它确实有效。谢谢。 – hmqcnoesy