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

前端 未结 5 1005
夕颜
夕颜 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).

提交回复
热议问题