属性クラス ( 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
クラス名は属性の名前 ( Author
) です。
System.Attribute
から派生しているため、カスタム属性クラスです。 コンストラクターのパラメーターは、カスタム属性の位置指定パラメーターです。 この例では、 name
は位置指定パラメーターです。 パブリック読み取り/書き込みフィールドまたはプロパティは、名前付きパラメーターです。 この場合、 version
は唯一の名前付きパラメーターです。
AttributeUsage
属性を使用して、Author
属性をクラスおよびStructure
宣言でのみ有効にしてください。
この新しい属性は次のように使用できます。
<Author("P. Ackerman", Version:=1.1)>
Class SampleClass
' P. Ackerman's code goes here...
End Class
AttributeUsage
には名前付きパラメーター AllowMultiple
があり、カスタム属性を単一使用または複数使用にすることができます。 次のコード例では、multiuse 属性が作成されます。
' multiuse attribute
<System.AttributeUsage(System.AttributeTargets.Class Or
System.AttributeTargets.Struct,
AllowMultiple:=True)>
Public Class Author
Inherits System.Attribute
次のコード例では、同じ型の複数の属性がクラスに適用されます。
<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
注
属性クラスにプロパティが含まれている場合、そのプロパティは読み取り/書き込みである必要があります。
こちらも参照ください
.NET