2012-04-27 382 views
5

屬性代碼繼承屬性

[AttributeUsage(AttributeTargets.Property, Inherited = true)] 
class IgnoreAttribute : Attribute 
{ 
} 

基類

abstract class ManagementUnit 
{ 
    [Ignore] 
    public abstract byte UnitType { get; } 
} 

Main類

class Region : ManagementUnit 
{ 
    public override byte UnitType 
    { 
     get { return 0; } 
    } 

    private static void Main() 
    { 
     Type t = typeof(Region); 
     foreach (PropertyInfo p in t.GetProperties()) 
     { 
      if (p.GetCustomAttributes(typeof(IgnoreAttribute), true).Length != 0) 
       Console.WriteLine("have attr"); 
      else 
       Console.WriteLine("don't have attr"); 
     } 
    } 
} 

輸出:don't have attr

解釋爲什麼會發生這種情況?畢竟,它必須繼承。

回答

5

繼承標誌指示屬性是否可以繼承。 此值的默認值爲false。但是,如果繼承標誌 設置爲true,則其含義取決於AllowMultiple 標誌的值。如果繼承標誌設置爲true,並且AllowMultiple標誌 爲false,則該屬性將覆蓋繼承的屬性。 但是,如果繼承標誌設置爲true並且AllowMultiple 標誌也設置爲true,則該屬性將在成員上累積。

http://aclacl.brinkster.net/InsideC/32ch09f.htm 檢查章節指定繼承屬性規則

編輯:檢查Inheritance of Custom Attributes on Abstract Properties 第一個答案:

這是GetCustomAttributes()方法,不看父母 聲明。它僅查看應用於指定的 成員的屬性。

+3

不,「繼承」的默認值是true。 https://msdn.microsoft.com/en-us/library/system.attributeusageattribute.inherited(v=vs.110).aspx – 00jt 2015-08-13 18:08:50