Share via


カスタム属性の作成 (C# および Visual Basic)

属性クラスを定義することで、独自のカスタム属性を作成できます。属性クラスは、Attribute の直接的または間接的な派生クラスです。Attribute により、メタデータの中で属性の定義をすばやく簡単に識別できます。 型にそれを記述したプログラマの名前でタグを付けるものとします。 Author というカスタム属性クラスを定義します。

<System.AttributeUsage(System.AttributeTargets.Class Or 
                       System.AttributeTargets.Struct)> 
Public Class Author
    Inherits System.Attribute
    Private name As String
    Public version As Double
    Sub New(ByVal authorName As String)
        name = authorName
        version = 1.0
    End Sub
End Class
[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct)
]
public class Author : System.Attribute
{
    private string name;
    public double version;

    public Author(string name)
    {
        this.name = name;
        version = 1.0;
    }
}

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

この新しい属性の使用方法は次のとおりです。

<Author("P. Ackerman", Version:=1.1)> 
Class SampleClass
    ' P. Ackerman's code goes here...
End Class
[Author("P. Ackerman", version = 1.1)]
class SampleClass
{
    // P. Ackerman's code goes here...
}

AttributeUsage には名前付きパラメーターの AllowMultiple があり、これを使ってカスタム属性が 1 回しか指定できない属性か、または複数回指定できる属性かを設定できます。 次のコード例では、複数回指定できる属性が作成されます。

' multiuse attribute
<System.AttributeUsage(System.AttributeTargets.Class Or 
                       System.AttributeTargets.Struct, 
                       AllowMultiple:=True)> 
Public Class Author
    Inherits System.Attribute
[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct,
                       AllowMultiple = true)  // multiuse attribute
]
public class Author : System.Attribute

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

<Author("P. Ackerman", Version:=1.1), 
Author("R. Koch", Version:=1.2)> 
Class SampleClass
    ' P. Ackerman's code goes here...
    ' R. Koch's code goes here...
End Class
[Author("P. Ackerman", version = 1.1)]
[Author("R. Koch", version = 1.2)]
class SampleClass
{
    // P. Ackerman's code goes here...
    // R. Koch's code goes here...
}

注意

属性クラスにプロパティが含まれている場合、そのプロパティは読み取り/書き込み可能である必要があります。

参照

参照

リフレクション (C# および Visual Basic)

属性 (C# および Visual Basic)

リフレクションを使用した属性へのアクセス (C# および Visual Basic)

System.Reflection

AttributeUsage (C# および Visual Basic)

概念

C# プログラミング ガイド

カスタム属性の記述

その他の技術情報

Visual Basic のプログラミング ガイド