Why does ICustomAttributeProvider.GetCustomAttributes() return object[] instead of Attribute[]?

Is there any circumstance when using the ICustomAttributeProvider implementations from mscorlib and System assemblies will return objects that are not of type Attribute?

有帮助吗?

解决方案

The CLI spec (ECMA 335) Partition II, Clause 21 states in part:

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.

In other words, a language that is not CLS-compliant may allow you to specify attributes that do not derive from Attribute, so the GetCustomAttributes method is probably designed to allow such attributes to be consumed.

I'm pretty sure that no such non-CLS-compliant language exists, and .NET doesn't support it, but one can imagine that the designers of Reflection did not want to preclude the possibility in the future.

As for your second question, a quick inspection of the source code for System.Reflection shows that you always get an Attribute[] back. Since the returned objects are always Attribute[], you can safely cast them, but there's no guarantee that it will always work that way.

其他提示

By taking a quick look with Reflector, in every place it is used they perform a safe cast to Attribute[], so I guess it is safe for you to do the same.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top