Reputation: 43523
Just curious, see MemberInfo.GetCustomAttributes
. Is it hinting that it may contain a non-Attribute object?
Upvotes: 13
Views: 1052
Reputation: 4154
In addition to what Reed said above, the MemberInfo.GetCustomAttributes
API lets you specify a filter type that influences the type of the array being returned. I.e., when you specify typeof (MyAttribute)
, the result will actually be a MyAttribute[]
(cast to object[]
).
Now, when you specify an interface type IMyAttribute
, the array is of type IMyAttribute[]
. And while it is possible to cast an IMyAttribute[]
to object[]
, it's not possible to cast it to Attribute[]
. So, in essence, were the result an Attribute[]
, filtering based on interfaces wouldn't work.
(BTW, the newer Attribute.GetCustomAttributes
APIs - which fixes the inheritance resolution for properties and events - have Attribute[]
as their return type. Which makes filtering based on interfaces impossible; you get an ArgumentException when trying to pass in an interface type for filtering.)
Upvotes: 2
Reputation: 564433
This is because the CLI specification doesn't enforce that attributes derive from Attribute.
The specification, in II Part 21 (page 225), states:
While any user-defined type can be used as an attribute, CLS compliance requires that attributes will be instances of types whose base class is System.Attribute. The CLI predefines some attribute types and uses them to control runtime behavior. Some languages predefine attribute types to represent language features not directly represented in the CTS. Users or other tools are welcome to define and use additional attribute types.
Basically, the CLR itself can't make a guarantee that the result will be Attribute - this is only true in CLS compliant languages. Non-CLS compliant languages are allowed to have attributes of any type, whic means ICustomAttributeProvider.GetCustomAttributes (which is the implemented interface in question) needs to provide a mechanism to get non-Attribute derived attributes.
Upvotes: 12
Reputation: 2943
Per MSDN: http://msdn.microsoft.com/en-us/library/kff8s254.aspx
This method ignores the inherit parameter for properties and events.
To search the inheritance chain for attributes on properties and events,
use the appropriate overloads of the Attribute.GetCustomAttributes method.
My understanding is it allows you can even custom an Attribute without inherit from System.Attribute but write totally your own "Attribute", with that flexibility, your "Attribute" can only be inherit Object sometimes
Upvotes: 0