【问题标题】:IL code for attribute inheritance属性继承的 IL 代码
【发布时间】:2013-05-06 13:19:25
【问题描述】:

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

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

有什么提示吗?

【问题讨论】:

  • 属性永远不会被继承,除非你指示它
  • NUnit 2.6.x 的 TestFixtureTeardown 属性怎么样?
  • 它在 NUnit 的文档中说 - “TestFixtureTearDown 属性是从任何基类继承的”。
  • 这发生在反射时,而不是编译时。
  • 这是否意味着运行时间?你能指点我一些有用的资源或阅读这个吗?谢谢。我知道我要求太多了:)

标签: c# compiler-construction attributes cil


【解决方案1】:

如果您应用在其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:

【讨论】:

  • 所以编译器没有做任何特别的事情,但是在运行时CLR会检查派生方法实现是否应用了属性?
  • 我只想知道编译器说此特定方法将应用此特定属性的部分。我将把这个标记为答案。
  • @KumarVaibhav 好吧,在继承属性的情况下,编译器不会这么说。
【解决方案2】:

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

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

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

[Custom]
public class Base {
}

public class Sub : Base {
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 2012-05-08
    • 2017-10-06
    • 1970-01-01
    • 2012-08-15
    • 2010-10-05
    • 1970-01-01
    相关资源
    最近更新 更多