如何使用反射(空引用)访问子类的const属性值?

时间:2017-07-27 19:50:55

标签: c# .net reflection

除了不好的做法外,我试图通过其属性值来获取过滤子类。

class Base
{
const string tag = "";
}

class A : Base
{
new const string tag = "ClassA";
}

class B : Base
{
new const string tag = "ClassB";
}

我知道const是隐式静态的,因此标签实际上并没有被继承,而只是与子类相关联。

然后,我想过滤到只有A类:

var result = Assembly.GetAssembly(typeof(Base))
.GetTypes()
.Where(t => t.BaseType == (typeof(Base))
.Where(t => ((string)t.GetProperty("tag").GetValue(null)).ToLower() == "classa")
.FirstOrDefault()

我在GetValue上呼叫null因为作为静态属性,我不应该在实例上调用GetValue。这来自Get value of a public static field via reflection

当我运行此代码时,我得到一个NullReferenceException。这不是一个理想的方法,但我受限于通过汇编和字符串比较。为什么我会得到空引用?

1 个答案:

答案 0 :(得分:2)

我认为您要查找字段,并使用FieldInfo.GetRawConstantValue()