2012-04-27 76 views
5

属性コード継承された属性

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

基本クラス

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

メインクラス

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 から

は継承属性の指定の章をチェックしてください

EDITルール: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

0

によって記録されるようPropertyInfo.GetCustomAttributesで継承フラグがプロパティおよびイベントの両方のために無視される:https://msdn.microsoft.com/en-us/library/dwc6ew1d.aspx。しかし、Attribute.GetCustomAttributesオーバーロードの1つを使用して、プロパティ(またはイベント)の継承を有効にすることができます。 http://blog.seancarpenter.net/2012/12/15/getcustomattributes-and-overridden-properties/

関連する問題