如果您应用在其AttributeUsage 属性中设置了Inherited = true 的属性,然后在从具有该属性的成员继承的成员上调用GetCustomAttributes(inherit: true),那么您将获得该属性。但是你不会在继承成员的 IL 中看到任何东西,编译器不会为它做任何特殊的事情,它是查看基成员的反射。
例如使用此代码:
[AttributeUsage(AttributeTargets.All, Inherited = true)]
class InheritedAttribute : Attribute
{}
[AttributeUsage(AttributeTargets.All, Inherited = false)]
class NotInheritedAttribute : Attribute
{}
abstract class Base
{
[Inherited, NotInherited]
public abstract void M();
}
class Derived : Base
{
public override void M()
{}
}
…
foreach (var type in new[] { typeof(Base), typeof(Derived) })
{
var method = type.GetMethod("M");
foreach (var inherit in new[] { true, false })
{
var attributes = method.GetCustomAttributes(inherit);
Console.WriteLine(
"{0}.{1}, inherit={2}: {3}",
method.ReflectedType.Name, method.Name, inherit,
string.Join(", ", attributes.Select(a => a.GetType().Name)));
}
}
你会得到这个输出:
Base.M, inherit=True: NotInheritedAttribute, InheritedAttribute
Base.M, inherit=False: NotInheritedAttribute, InheritedAttribute
Derived.M, inherit=True: InheritedAttribute
Derived.M, inherit=False: