只是好奇,请参阅 MemberInfo.GetCustomAttributes
。是否暗示它可能包含非属性对象?
最佳答案
这是因为 CLI 规范不强制要求属性派生自 Attribute。
规范,在 II Part 21 中(第 225 页),指出:
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.
基本上,CLR 本身不能保证结果将是 Attribute - 这仅适用于 CLS 兼容语言。允许不符合 CLS 的语言具有任何类型的属性,这意味着 ICustomAttributeProvider.GetCustomAttributes (这是有问题的已实现接口(interface))需要提供一种机制来获取非属性派生属性。
关于c# - 为什么 GetCustomAttributes 返回 object[] 而不是 Attribute[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9511511/