PropertyInfo.GetCustomAttributes() Doesn't Return Inherited Attributes
|
The article you are reading has moved! It is now available at: http://blog.tinisles.com/2008/03/propertyinfo-getcustomattributes-doesnt-return-inherited-attributes/ |
Here's a problem I ran into today. If you have an attribute on the property of a base class; are you able to read it via PropertyInfo.GetCustomAttributes on the properties of a subclass.
Here's where it helps to read the fine print. PropertyInfo.GetCustomAttributes takes a parameter for 'inherit' - yet the reference for PropertyInfo contains some important details:
Calling ICustomAttributeProvider.GetCustomAttributes on PropertyInfo when the inherit parameter of GetCustomAttributes is true does not walk the type hierarchy. Use System.Attribute to inherit custom attributes.
The code to read the attributes ended up looking like this:
foreach (PropertyInfo property in type.GetProperties()) { // not this one -> property.GetCustomAttributes(true); Attribute[] attributes = Attribute.GetCustomAttributes(property); }
Cheers, was bashing my head against the same issue.
Posted by Markie | 2:44 am