How to get a Static property with Reflection

后端 未结 8 1271
旧巷少年郎
旧巷少年郎 2020-11-28 05:44

So this seems pretty basic but I can\'t get it to work. I have an Object, and I am using reflection to get to it\'s public properties. One of these properties is static an

相关标签:
8条回答
  • 2020-11-28 06:48

    This is C#, but should give you the idea:

    public static void Main() {
        typeof(Program).GetProperty("GetMe", BindingFlags.NonPublic | BindingFlags.Static);
    }
    
    private static int GetMe {
        get { return 0; }
    }
    

    (you need to OR NonPublic and Static only)

    0 讨论(0)
  • 2020-11-28 06:48

    Just wanted to clarify this for myself, while using the new reflection API based on TypeInfo - where BindingFlags is not available reliably (depending on target framework).

    In the 'new' reflection, to get the static properties for a type (not including base class(es)) you have to do something like:

    IEnumerable<PropertyInfo> props = 
      type.GetTypeInfo().DeclaredProperties.Where(p => 
        (p.GetMethod != null && p.GetMethod.IsStatic) ||
        (p.SetMethod != null && p.SetMethod.IsStatic));
    

    Caters for both read-only or write-only properties (despite write-only being a terrible idea).

    The DeclaredProperties member, too doesn't distinguish between properties with public/private accessors - so to filter around visibility, you then need to do it based on the accessor you need to use. E.g - assuming the above call has returned, you could do:

    var publicStaticReadable = props.Where(p => p.GetMethod != null && p.GetMethod.IsPublic);
    

    There are some shortcut methods available - but ultimately we're all going to be writing a lot more extension methods around the TypeInfo query methods/properties in the future. Also, the new API forces us to think about exactly what we think of as a 'private' or 'public' property from now on - because we must filter ourselves based on individual accessors.

    0 讨论(0)
提交回复
热议问题