How to get a Static property with Reflection

后端 未结 8 1270
旧巷少年郎
旧巷少年郎 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:26
    myType.GetProperties(BindingFlags.Public | BindingFlags.Static |  BindingFlags.FlattenHierarchy);
    

    This will return all static properties in static base class or a particular type and probably the child as well.

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

    Or just look at this...

    Type type = typeof(MyClass); // MyClass is static class with static properties
    foreach (var p in type.GetProperties())
    {
       var v = p.GetValue(null, null); // static classes cannot be instanced, so use null...
    }
    
    0 讨论(0)
  • 2020-11-28 06:35

    Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:

    obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
      Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
      Reflection.BindingFlags.FlattenHierarchy)
    
    0 讨论(0)
  • 2020-11-28 06:40

    The below seems to work for me.

    using System;
    using System.Reflection;
    
    public class ReflectStatic
    {
        private static int SomeNumber {get; set;}
        public static object SomeReference {get; set;}
        static ReflectStatic()
        {
            SomeReference = new object();
            Console.WriteLine(SomeReference.GetHashCode());
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            var rs = new ReflectStatic();
            var pi = rs.GetType().GetProperty("SomeReference",  BindingFlags.Static | BindingFlags.Public);
            if(pi == null) { Console.WriteLine("Null!"); Environment.Exit(0);}
            Console.WriteLine(pi.GetValue(rs, null).GetHashCode());
    
    
        }
    }
    
    0 讨论(0)
  • 2020-11-28 06:43

    A little clarity...

    // Get a PropertyInfo of specific property type(T).GetProperty(....)
    PropertyInfo propertyInfo;
    propertyInfo = typeof(TypeWithTheStaticProperty)
        .GetProperty("NameOfStaticProperty", BindingFlags.Public | BindingFlags.Static); 
    
    // Use the PropertyInfo to retrieve the value from the type by not passing in an instance
    object value = propertyInfo.GetValue(null, null);
    
    // Cast the value to the desired type
    ExpectedType typedValue = (ExpectedType) value;
    
    0 讨论(0)
  • 2020-11-28 06:47

    Try this C# Reflection link.

    Note I think that BindingFlags.Instance and BindingFlags.Static are exclusive.

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