AttributeUsage (C# プログラミング ガイド)
更新 : 2007 年 11 月
カスタムの属性クラスの使用方法を決定します。AttributeUsage は、新しい属性の適用方法を制御するカスタムの属性定義に適用できる属性です。既定の設定を明示的に割り当てると、次のようになります。
[System.AttributeUsage(System.AttributeTargets.All,
AllowMultiple=false,
Inherited=true)]
class NewAttribute : System.Attribute { }
この例では、NewAttribute クラスは、属性を使用できるコード要素すべてに適用できますが、各要素に適用できるのは 1 つだけです。基本クラスに適用すると、派生クラスによって継承されます。
AllowMultiple 引数と Inherited 引数はオプションなので、次のコードでも同じ効果があります。
[System.AttributeUsage(System.AttributeTargets.All)]
class NewAttribute : System.Attribute { }
最初の AttributeUsage 引数は、AttributeTargets 列挙体の 1 つ以上の要素にする必要があります。複数の型を対象にする場合、次のように OR 接続できます。
using System;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
class NewPropertyOrFieldAttribute : Attribute { }
次のように AllowMultiple 引数を true に設定すると、1 つの要素に結果の属性を複数適用できます。
using System;
[AttributeUsage(AttributeTargets.Class, AllowMultiple=true)]
class MultiUseAttr : Attribute { }
[MultiUseAttr][MultiUseAttr]
class Class1 { }
[MultiUseAttr, MultiUseAttr]
class Class2 { }
この場合、AllowMultiple が true に設定されているため、MultiUseAttr を繰り返し適用できます。複数の属性を適用する場合、どちらの形式でも有効です。
Inherited を false に設定した場合、属性を指定したクラスから派生するクラスには、属性が継承されません。次に例を示します。
using System;
[AttributeUsage(AttributeTargets.Class, Inherited=false)]
class Attr1 : Attribute { }
[Attr1]
class BClass { }
class DClass : BClass { }
この場合、Attr1 は 継承によって DClass に適用されません。
解説
AttributeUsage 属性は、シングルユースの属性です。同一のクラスに複数回適用することはできません。AttributeUsage は、AttributeUsageAttribute のエイリアスです。
詳細については、「リフレクションによる属性へのアクセス (C# プログラミング ガイド)」を参照してください。
使用例
次の例は、Inherited 引数と AllowMultiple 引数を AttributeUsage 属性に指定する影響と、クラスに適用されるカスタム属性の列挙方法に関するデモンストレーションです。
using System;
// Create some custom attributes:
[AttributeUsage(System.AttributeTargets.Class, Inherited=false)]
class A1 : System.Attribute { }
[AttributeUsage(System.AttributeTargets.Class)]
class A2 : System.Attribute { }
[AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true)]
class A3 : System.Attribute { }
// Apply custom attributes to classes:
[A1,A2]
class BaseClass { }
[A3,A3]
class DerivedClass : BaseClass { }
public class TestAttributeUsage
{
static void Main()
{
BaseClass b = new BaseClass();
DerivedClass d = new DerivedClass();
// Display custom attributes for each class.
Console.WriteLine("Attributes on Base Class:");
object[] attrs = b.GetType().GetCustomAttributes(true);
foreach (Attribute attr in attrs)
{
Console.WriteLine(attr);
}
Console.WriteLine("Attributes on Derived Class:");
attrs = d.GetType().GetCustomAttributes(true);
foreach (Attribute attr in attrs)
{
Console.WriteLine(attr);
}
}
}
出力例
Attributes on Base Class:
A1
A2
Attributes on Derived Class:
A3
A3
A2