jeudi 27 juillet 2017

How do I access a subclass's const property value with reflection (null reference)?

Poor practice aside, I'm trying to get filter subclasses by their property values.

class Base
{
const string tag = "";
}

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

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

I know that const is implicitly static, and so the tags aren't actually inherited, but instead are just associated with the subclasses.

Then, I want to filter to only Class 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()

I'm calling GetValue on null because as a static property, I shouldn't call GetValue on an instance. This is from Get value of a public static field via reflection

When I run this code, I get a NullReferenceException. This is not an ideal way of doing this, but I am constrained to getting by assembly and comparing by string. Why would I be getting the null reference?





Aucun commentaire:

Enregistrer un commentaire