c# - 为什么 GetCustomAttributes 返回 object[] 而不是 Attribute[]?

标签 c# .net reflection attributes

只是好奇,请参阅 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/

相关文章:

c# - 如何正确读取 Interlocked.Increment'ed int 字段?

c# - 如何对轮廓进行排序?

c# - 如何在C#中使用反射来区分具有相同属性的类成员

c# - 如何使用反射调试从 app.config 加载的对象?

c# - 保存对话框消息和空路径名

c# - 根据数据库选择突出显示/禁用ajax日历控件中的特定日期

c# - 正则表达式仅捕获 [0-9] 数字,同时将数字与空格或逗号匹配

.net - EF Core linq 和条件包含然后包含问题

c# - 添加时 Entity Framework SaveChanges

c# - 检索 Action 签名自定义属性