Skip to main content
 首页 » 编程设计

c#之Attribute.IsDefined 与 MemberInfo.IsDefined之继承参数的区别

2024年02月05日11sxdcgaq8080

我的问题涉及检查属性的继承属性。

如 this Question 中所述方法 Attribute.IsDefined(MemberInfo, Type, Boolean) (1) 和 MemberInfo.IsDefined(Type, Boolean) (2)基本相同。两者都在检查是否使用了属性。但是如果我想检查一个属性,继承参数会有很大的不同:

(1):

If true, specifies to also search the ancestors of element for custom attributes.

(2):

true to search this member's inheritance chain to find the attributes; otherwise, false.This parameter is ignored for properties and events; see Remarks.

(备注只推荐使用(1))

使用(1) 获取属性的继承属性是没有问题的。但我的问题是为什么:为什么这个功能是这样实现的?原因、用途或好处是什么?在我看来,有一种方法会忽略参数,这并不是一个真正干净的解决方案。

我是不是忽略了什么?

请您参考如下方法:

我的猜测(它是不再是猜测)- 原因是向后兼容性。

PropertyInfo.IsDefined 和 EventInfo.IsDefined 忽略了 inherit 参数,因为它们是在 .NET 1.0 中引入的。 Attribute 上的静态方法是在 .NET 2.0 中引入的,并经过修改以支持属性和事件的继承。如果他们要更改该行为,将 inherit 设置为 true 的旧代码可能会开始获得意外的属性。

只是 BCL 中众多不一致的地方之一……:)