How to get a Static property with Reflection

后端 未结 8 1320
旧巷少年郎
旧巷少年郎 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: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());
    
    
        }
    }
    

提交回复
热议问题