views:

44

answers:

2

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?

+1  A: 

Add BindingFlags.FlattenHierarchy:

       GetField("x", BindingFlags.NonPublic  | BindingFlags.Static | BindingFlags.FlattenHierarchy).GetValue(null) as double?;
Andrey
+2  A: 
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;
Ani
no, i have 20 variables, in base class, and i want to loop them, with some restriction on their names
eba