Reputation: 979
I want to get value of field of base class, in child class, by name of field:
class A
{
protected static double? x;
}
class B : A
{
B()
: base()
{
x = 13F;
}
void test()
{
double? s = this.GetType().
GetField("x", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null) as double?;
}
}
why i have TargetException, when i call test() method?
Upvotes: 0
Views: 659
Reputation: 113472
double? s = GetType()
.GetField("x", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Static)
.GetValue(null) as double?;
From System.Reflection.BindingFlags
:
FlattenHierarchy: Specifies that public and protected static members up the hierarchy should be returned. Private static members in inherited classes are not returned. Static members include fields, methods, events, and properties. Nested types are not returned.
I assume this is just a toy example to test reflecting static members in base types? Otherwise, it appears a little strange to use reflection in this context: protected
members are visible to subclasses. You could just do:
double? s = x;
Upvotes: 2
Reputation: 60105
Add BindingFlags.FlattenHierarchy
:
GetField("x", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy).GetValue(null) as double?;
Upvotes: 1