Why does GetCustomAttributes return an object [] instead of the attribute []?

Just curious, see MemberInfo.GetCustomAttributes . Is this a hint that it might contain an object without an attribute?

+8
reflection c # attributes
source share
3 answers

This is because the CLI specification does not ensure that these attributes are derived from an attribute.

Specification II Part 21 (p. 225) states:

While any custom type can be used as an attribute, CLS matching requires that attributes be instances of types whose base class is System.Attribute. The CLI predefines certain types of attributes and uses them to control runtime. Some languages ​​predefine attribute types to represent language functions directly represented in CTS. Users or other tools can define and use additional types of attributes.

In principle, the CLR itself cannot guarantee that the result will be an attribute - this is true only for languages ​​compatible with CLS. Non-CLS compatible languages ​​can have attributes of any type, which means ICustomAttributeProvider.GetCustomAttributes (which is an implemented interface) should provide a mechanism for obtaining attributes that are not associated with an attribute.

+8
source share

On 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. 

I understand that it even allows you to customize an attribute without inheriting from System.Attribute, but completely write your own "attribute", with such flexibility your "attribute" can inherit Object sometimes

0
source share

In addition to what Reid said above, MemberInfo.GetCustomAttributes API allows you to specify the type of filter that affects the type of array returned. Ie, when you specify typeof (MyAttribute) , the result will actually be MyAttribute[] (discarded to object[] ).

Now, when you specify the IMyAttribute interface IMyAttribute , the array is of the IMyAttribute[] . Although IMyAttribute[] can be dropped to object[] , it cannot be dropped to Attribute[] . Thus, in essence, this was the result of Attribute[] , filtering based on interfaces did not work.

(BTW, the new Attribute.GetCustomAttributes APIs that capture inheritance resolution for properties and events have Attribute[] as their return type. This makes filtering based on interfaces impossible, you get an ArgumentException when trying to pass an interface type for filtering.)

0
source share

All Articles