为什么GetCustomAttributes(true)不返回AttributeUsageAttribute.Inherited = false(AttributeUsageAttribute.Inherited = false)的属性(https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(System.AttributeUsageAttribute.Inherited%29;k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.6.1%29;k(DevLang-csharp%29&rd=true)?文档中没有提到这两者应该相互作用的东西)。下面的代码输出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);
}
}发布于 2017-09-29 11:29:07
Type.GetCustomAttributes()是一个扩展方法,它调用Attribute.GetCustomAttributes(),然后调用参数inherit设置为true的GetCustomAttributes。因此,默认情况下,在使用GetCustomAttributes()时,您已经在继承。
因此,唯一的区别是GetCustomAttributes()和GetCustomAttributes(inherit: false)。后者将禁用可继承属性的继承,而前者只会传递那些可继承的属性。
不能强制本身不可继承的属性是可继承的.
请参阅下面的示例以获得快速摘要:
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 { }https://stackoverflow.com/questions/46487663
复制相似问题