Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么GetCustomAttributes返回对象[]而不是属性[]?_C#_.net_Reflection_Attributes - Fatal编程技术网

C# 为什么GetCustomAttributes返回对象[]而不是属性[]?

C# 为什么GetCustomAttributes返回对象[]而不是属性[]?,c#,.net,reflection,attributes,C#,.net,Reflection,Attributes,只是好奇,请参见MemberInfo.GetCustomAttributes。它是否暗示它可能包含非属性对象 根据MSDN: 我的理解是,它允许您甚至可以自定义一个属性,而无需从System.Attribute继承。但完全编写您自己的“属性”,有了这种灵活性,您的“属性”有时只能是继承对象,这是因为CLI规范没有强制要求属性从属性派生 规范(第225页)规定: 当 任何用户定义的类型都可以用作属性,CLS合规性要求属性将是 基类为System.Attribute的类型。CLI预定义了一些属性类型

只是好奇,请参见
MemberInfo.GetCustomAttributes
。它是否暗示它可能包含非属性对象

根据MSDN:


我的理解是,它允许您甚至可以自定义一个属性,而无需从System.Attribute继承。但完全编写您自己的“属性”,有了这种灵活性,您的“属性”有时只能是继承对象,这是因为CLI规范没有强制要求属性从属性派生

规范(第225页)规定:

当 任何用户定义的类型都可以用作属性,CLS合规性要求属性将是 基类为System.Attribute的类型。CLI预定义了一些属性类型并使用它们来控制 运行时行为。某些语言预定义属性类型以不直接表示语言功能 在CTS中有代表性。欢迎用户或其他工具定义和使用其他属性类型


基本上,CLR本身不能保证结果是属性-这仅在符合CLS的语言中是正确的。不符合CLS的语言允许具有任何类型的属性,这意味着(这是正在讨论的实现接口)需要提供一种机制来获取非属性派生属性。

除了Reed上面所说的,通过
MemberInfo.GetCustomAttributes
API,可以指定影响返回数组类型的筛选器类型。也就是说,当您指定
typeof(MyAttribute)
时,结果实际上将是一个
MyAttribute[]
(强制转换为
object[]

现在,当您指定接口类型
IMyAttribute
时,数组的类型为
IMyAttribute[]
。虽然可以将
IMyAttribute[]
强制转换为
对象[]
,但无法将其强制转换为
属性[]
。因此,本质上,如果结果是
属性[]
,基于接口的过滤将无法工作

(顺便说一句,更新的
Attribute.GetCustomAttributes
API—它修复了属性和事件的继承解析—将
Attribute[]
作为其返回类型。这使得基于接口的过滤不可能;当尝试传递用于过滤的接口类型时,会出现ArgumentException。)

+1用于提及。使用这些API通常可以避免额外的
ToArray()
调用。
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.