简体   繁体   中英

C# reflection base class trouble

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?

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;

添加BindingFlags.FlattenHierarchy

       GetField("x", BindingFlags.NonPublic  | BindingFlags.Static | BindingFlags.FlattenHierarchy).GetValue(null) as double?;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM