为什么 GetCustomAttributes(true)
不返回 AttributeUsageAttribute.Inherited = false
的返回属性?我可以看到文档中没有任何东西说这两个应该相互作用。以下代码输出0
。
class Program
{
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
class NotInheritedAttribute : Attribute { }
[NotInherited]
class A { }
class B : A { }
static void Main(string[] args)
{
var attCount = typeof(B).GetCustomAttributes(true).Count();
Console.WriteLine(attCount);
}
}
Type.GetCustomAttributes()
是一种扩展方法,该方法调用attribute.getCustomattributes(),依次调用 GetCustomAttributes
,将参数 inherit
设置为 true
。因此,默认情况下,您使用GetCustomAttributes()
时已经继承了。
因此,唯一的区别是GetCustomAttributes()
和GetCustomAttributes(inherit: false)
。后者将 disable 继承的属性,而前者只会通过那些可以通过的属性。
您不能强迫自己无可遗忘的属性。
请参阅以下示例以获取快速摘要:
void Main()
{
typeof(A).GetCustomAttributes().Dump(); // both
typeof(A).GetCustomAttributes(inherit: false).Dump(); // both
typeof(B).GetCustomAttributes().Dump(); // inheritable
typeof(B).GetCustomAttributes(inherit: false).Dump(); // none because inheritance is prevented
typeof(C).GetCustomAttributes().Dump(); // both
typeof(C).GetCustomAttributes(inherit: false).Dump(); // both because C comes with its own copies
}
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class InheritableExampleAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class NonInheritableExampleAttribute : Attribute { }
[InheritableExample]
[NonInheritableExample]
public class A { }
public class B : A { }
[InheritableExample]
[NonInheritableExample]
public class C : A { }