How do you get the all properties of a class and its base classes (up the hierarchy) with Reflection? (C#)

前端 未结 5 1003
夕颜
夕颜 2020-11-30 08:48

So what I have right now is something like this:

PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public);

where obj

5条回答
  •  [愿得一人]
    2020-11-30 09:17

    I don't think it's that complicated.

    If you remove the BindingFlags parameter to GetProperties, I think you get the results you're looking for:

        class B
        {
            public int MyProperty { get; set; }
        }
    
        class C : B
        {
            public string MyProperty2 { get; set; }
        }
    
        static void Main(string[] args)
        {
            PropertyInfo[] info = new C().GetType().GetProperties();
            foreach (var pi in info)
            {
                Console.WriteLine(pi.Name);
            }
        }
    

    produces

        MyProperty2
        MyProperty
    

提交回复
热议问题