为什么 ICustomAttributeProvider.GetCustomAttributes() 返回 object[] 而不是 Attribute[]?
为什么 ICustomAttributeProvider.GetCustomAttributes()
返回 object[]
而不是 Attribute[]
?
使用 mscorlib 和系统程序集的 ICustomAttributeProvider
实现时,是否存在任何情况会返回非 Attribute
类型的对象?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CLI 规范 (ECMA 335) 分区 II ,第 21 条部分规定:
换句话说,不符合 CLS 的语言可能允许您指定不是从
Attribute
派生的属性,因此GetCustomAttributes
方法可能被设计为允许此类属性被消耗。我很确定不存在这样的不符合 CLS 的语言,并且 .NET 也不支持它,但可以想象 Reflection 的设计者并不想排除将来这种可能性。
至于你的第二个问题,快速检查
System.Reflection
的源代码表明你总是得到一个Attribute[]
返回。由于返回的对象始终是Attribute[]
,因此您可以安全地转换它们,但不能保证它总是以这种方式工作。The CLI spec (ECMA 335) Partition II, Clause 21 states in part:
In other words, a language that is not CLS-compliant may allow you to specify attributes that do not derive from
Attribute
, so theGetCustomAttributes
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 anAttribute[]
back. Since the returned objects are alwaysAttribute[]
, you can safely cast them, but there's no guarantee that it will always work that way.通过使用 Reflector 快速浏览一下,在使用它的每个地方,它们都会对 Attribute[] 执行安全转换,因此我想您也可以安全地执行相同的操作。
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.