1

我在这里有一个基本问题。我在基类中的抽象方法上有一个属性。现在,当我在某个派生类中实现/覆盖此方法时,我看不到在为该派生类方法生成的 IL 中应用的属性。但这一切都很好。

我在这里错过了什么吗?我们如何知道编译器已将派生类方法实现标记为由该特定属性修饰?

有什么提示吗?

4

2 回答 2

2

如果您应用已Inherited = true在其属性中设置的AttributeUsage属性,然后调用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:
于 2013-05-06T14:42:34.337 回答
1

默认情况下,属性不会应用于派生类,除非您在创建时明确指示它。

AttributesUsage属性有一个名为Inherited的属性(布尔类型),它告诉您的属性是否会被派生类继承。

[AttributeUsage( Inherited = true)]
public class CustomAttribute : Attribute
{
}

[Custom]
public class Base {
}

public class Sub : Base {
}

现在它CustomAttribute也被子类应用/继承。

于 2013-05-06T13:26:30.333 回答