2009-08-06 55 views
82

属性上的Inherited bool属性是指什么?继承对属性如何工作?

是否意味着如果我使用属性AbcAtribute(即Inherited = true)定义了我的类,并且如果我从该类继承另一个类,那么派生类也会将相同的属性应用于它?

要澄清一个代码示例这个问题,设想以下:

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

[Random] 
class Mother 
{ } 

class Child : Mother 
{ } 

是否Child也有适用于它的Random属性?

+0

当你问这个问题时,情况并非如此,而是今天[继承的属性的官方文档](https://msdn.microsoft.com/en-us/library/system.attributeusageattribute.inherited。 aspx)有一个精心设计的例子,它显示了继承类和覆盖方法的'Inherited = true'和'Inherited = false'之间的区别。 – 2017-08-28 20:31:38

回答

88

当继承=真(这是默认值)则意味着要创建的属性可通过将装饰属性的类的子类继承。

所以 - 如果你创建MyUberAttribute与[AttributeUsage(继承= TRUE)]

[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 
{ 
    ... 
} 

然后实例化一个instanc MySubClass电子...

MySubClass MySubClassInstance = new MySubClass(); 

然后进行测试,看它是否具有属性...

MySubClassInstance < ---现在有 “鲍勃” 作为SpecialName值MyUberAttribute。

+12

请注意,属性继承默认是启用的。 – 2015-08-27 13:27:07

12

是的,这正是它的意思。 Attribute

[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());