Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using reflection to get at properties, How can I limit my search to just the subclass I'm interested in?

After successfully getting a list of specific types out of an assembly using reflection, I now want to get at the public properties of each of those.

Each of these types derives from at least one base class.

I notice when I get properties on a type that I get properties from the base classes as well.

I need a way to filter out base class properties and only get back the properties for the type that I am calling get properties on.

I reckon it would be similar to how I'm only getting sub classes of a base type, excluding the base type, from a given base type.

Assembly.GetAssembly(baseType).GetTypes().Where(type => type.IsSubclassOf(baseType)).ToList()
like image 529
topwik Avatar asked Aug 18 '09 14:08

topwik


1 Answers

Use BindingFlags.DeclaredOnly in your call to Type.GetProperties:

var properties = Type.GetProperties(BindingFlags.DeclaredOnly | 
                                    BindingFlags.Public |
                                    BindingFlags.Instance);
like image 78
Jon Skeet Avatar answered Dec 28 '22 10:12

Jon Skeet