次の方法で共有


カスタム属性を作成する

属性クラス ( Attributeから直接または間接的に派生するクラス) を定義することで、独自のカスタム属性を作成できます。これにより、メタデータ内の属性定義を迅速かつ簡単に識別できます。 型を記述したプログラマの名前で型にタグを付けたいとします。 カスタム Author 属性クラスを定義できます。

[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct)
]
public class AuthorAttribute : System.Attribute
{
    private string Name;
    public double Version;

    public AuthorAttribute(string name)
    {
        Name = name;
        Version = 1.0;
    }
}

AuthorAttributeクラス名は、属性の名前 、Author、およびAttributeサフィックスです。 System.Attributeから派生しているため、カスタム属性クラスです。 コンストラクターのパラメーターは、カスタム属性の位置指定パラメーターです。 この例では、 name は位置指定パラメーターです。 パブリック読み取り/書き込みフィールドまたはプロパティは、名前付きパラメーターです。 この場合、 version は唯一の名前付きパラメーターです。 AttributeUsage属性を使用して、Author属性をクラスおよびstruct宣言でのみ有効にしてください。

この新しい属性は次のように使用できます。

[Author("P. Ackerman", Version = 1.1)]
class SampleClass
{
    // P. Ackerman's code goes here...
}

AttributeUsage には名前付きパラメーター AllowMultipleがあり、カスタム属性を単一使用または複数使用にすることができます。 次のコード例では、multiuse 属性が作成されます。

[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct,
                       AllowMultiple = true)  // Multiuse attribute.
]
public class AuthorAttribute : System.Attribute
{
    string Name;
    public double Version;

    public AuthorAttribute(string name)
    {
        Name = name;

        // Default value.
        Version = 1.0;
    }

    public string GetName() => Name;
}

次のコード例では、同じ型の複数の属性がクラスに適用されます。

[Author("P. Ackerman"), Author("R. Koch", Version = 2.0)]
public class ThirdClass
{
    // ...
}

こちらも参照ください