Filter properties returned by TypeDescriptor.GetPr

2019-08-15 02:51发布

问题:

Hey guys. I have the following situation.

I want to use a TypeDescriptor to get the properties of a certain type. The type's depth in the inheritance hierarchy may vary. I only want to get the properties declared in the type itself and not in its parents (base). The problem is that when I call TypeDescriptor.GetProperties() it would return everything declared up the inheritance hierarchy up to Object.

I only saw that I can filter the output by Attributes, but I don't want to add another attribute to the properties in my types just for this. Getting them through reflection and not using TypeDescriptor would do what I want, but is not an option for me, because some of the properties will be added dynamically to the type at some point.

Any ideas? If the question is not clear I could provide an example.

回答1:

You can filter the properties using the ComponentType property :

var properties = from p in TypeDescriptor.GetProperties(x).Cast<PropertyDescriptor>()
                 where p.ComponentType == x.GetType()
                 select p;


回答2:

Can't you just modify the implementation of ICustomTypeDescriptor to reflect your desired behavior?