只是好奇,看到
MemberInfo.GetCustomAttributes
。这是否暗示它可能包含一个非属性对象?MemberInfo.GetCustomAttributes
。这是否暗示它可能包含一个非属性对象?MemberInfo.GetCustomAttributes
API允许您指定一个过滤器类型,影响返回的数组类型。也就是说,当您指定typeof(MyAttribute)
时,结果实际上将是一个MyAttribute[]
(强制转换为object[]
)。IMyAttribute
时,该数组的类型为IMyAttribute[]
。虽然可以将IMyAttribute[]
强制转换为object[]
,但无法将其强制转换为Attribute[]
。因此,从本质上讲,如果结果是Attribute[]
,则基于接口的过滤将不起作用。Attribute.GetCustomAttributes
API - 修复了属性和事件的继承解析 - 其返回类型为Attribute[]
。这使得基于接口的过滤成为不可能;尝试传入一个接口类型进行过滤时会引发ArgumentException。)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.
我的理解是,它允许你甚至可以自定义一个属性而不必继承自System.Attribute,完全编写你自己的“Attribute”,有了这种灵活性,你的“Attribute”有时只能继承Object。
ToArray()
调用。通过这些 API,通常可以避免这种情况的发生。 - l33t