2009-08-06 78 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());