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

前端 未结 5 988
夕颜
夕颜 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:09

    I would tend to agree with Nicolas; unless you know you need reflection, then ComponentModel is a viable alternative, with the advantage that you will get the correct metadata even for runtime models (such as DataView/DataRowView).

    For example:

        foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))
        {
            Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obj));
        }
    

    As an aside, you can also do some simple performance tricks with this; you can do the same with reflection and Delegate.CreateDelegate, but there is no centralised place to hide the logic away, unlike TypeDescriptor with a TypeDescriptionProvider (don't worry if these are unfamiliar; you can just use the code "as is" ;-p).

    0 讨论(0)
  • 2020-11-30 09:11

    Use:

    TypeDescriptor.GetProperties(obj);
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-30 09:20

    If you access Type.BaseType, you can get the base type. You can recursively access each base type and you'll know when you've hit the bottom when your type is System.Object.

    Type type = obj.GetType();
    PropertyInfo[] info = type.GetProperties(BindingFlags.Public);
    PropertyInfo[] baseProps = type.BaseType.GetProperties(BindingFlags.Public);
    
    0 讨论(0)
  • 2020-11-30 09:26

    Use this:

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

    EDIT: Of course the correct answer is that of Jay. GetProperties() without parameters is equivalent to GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static ). The BindingFlags.FlattenHierarchy plays no role here.

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