属性的继承是如何工作的?

131

Inherited属性是什么意思?

这是否意味着,如果我使用一个具有Inherited = true的属性AbcAtribute定义我的类,并从该类继承另一个类,那么派生类也将应用相同的属性?

为了通过代码示例澄清这个问题,请想象以下情况:

[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class Random: Attribute
{ /* attribute logic here */ }

[Random]
class Mother 
{ }

class Child : Mother 
{ }

子元素Child是否也应用了Random属性?


4
当你提出这个问题时,情况并非如此,但今天的Inherited属性的官方文档有一个详细的例子,展示了继承类和override方法中Inherited=trueInherited=false之间的区别。 - Jeppe Stig Nielsen
3个回答

141

当 Inherited = true 时(这是默认值),表示你正在创建的属性可以被装饰有该属性的类的子类继承。

因此,如果您使用 [AttributeUsage(Inherited = true)] 创建 MyUberAttribute,则意味着该属性可以被 MyUberAttribute 的子类继承。

[AttributeUsage (Inherited = True)]
MyUberAttribute : Attribute
{
   string _SpecialName;
   public string SpecialName
   { 
     get { return _SpecialName; }
     set { _SpecialName = value; }
   }
}

然后通过装饰一个超类来使用该属性...

[MyUberAttribute(SpecialName = "Bob")]
class MySuperClass 
{
  public void DoInterestingStuf () { ... }
}
如果我们创建MySuperClass的子类,它将具有此属性...
class MySubClass : MySuperClass
{
   ...
}

然后实例化一个 MySubClass 的实例...

MySubClass MySubClassInstance = new MySubClass();

然后测试是否有该属性...

现在,MySubClassInstance已经具有了MyUberAttribute,其SpecialName值为"Bob"。


18

是的,那正是它的意思。 属性

[AttributeUsage(Inherited=true)]
public class FooAttribute : System.Attribute
{
    private string name;

    public FooAttribute(string name)
    {
        this.name = name;
    }

    public override string ToString() { return this.name; }
}

[Foo("hello")]
public class BaseClass {}

public class SubClass : BaseClass {}

// outputs "hello"
Console.WriteLine(typeof(SubClass).GetCustomAttributes(true).First());

3

属性继承默认是启用的。

您可以通过以下方式更改此行为:

[AttributeUsage (Inherited = False)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接