カスタム属性を定義してソース コードに配置できることは、その情報を何らかの方法で取得して処理することなく、ほとんど価値がありません。 リフレクションを使用すると、カスタム属性で定義された情報を取得できます。 キー メソッドは GetCustomAttributes
であり、ソース コード属性に相当する実行時のオブジェクトの配列を返します。 このメソッドには、いくつかのオーバー ロード バージョンがあります。 詳細については、Attributeを参照してください。
次のような属性の仕様。
<Author("P. Ackerman", Version:=1.1)>
Class SampleClass
' P. Ackerman's code goes here...
End Class
は概念的にはこれと同等です。
Dim anonymousAuthorObject As Author = New Author("P. Ackerman")
anonymousAuthorObject.version = 1.1
ただし、 SampleClass
属性のクエリが実行されるまで、コードは実行されません。 GetCustomAttributes
でSampleClass
を呼び出すと、Author
オブジェクトが上記のように構築および初期化されます。 クラスに他の属性がある場合、他の属性オブジェクトも同様に構築されます。 GetCustomAttributes
次に、 Author
オブジェクトと配列内のその他の属性オブジェクトを返します。 その後、この配列を反復処理し、各配列要素の型に基づいて適用された属性を決定し、属性オブジェクトから情報を抽出できます。
例
完全な例を次に示します。 カスタム属性が定義され、複数のエンティティに適用され、リフレクションによって取得されます。
' Multiuse attribute
<System.AttributeUsage(System.AttributeTargets.Class Or
System.AttributeTargets.Struct,
AllowMultiple:=True)>
Public Class Author
Inherits System.Attribute
Private name As String
Public version As Double
Sub New(ByVal authorName As String)
name = authorName
' Default value
version = 1.0
End Sub
Function GetName() As String
Return name
End Function
End Class
' Class with the Author attribute
<Author("P. Ackerman")>
Public Class FirstClass
End Class
' Class without the Author attribute
Public Class SecondClass
End Class
' Class with multiple Author attributes.
<Author("P. Ackerman"), Author("R. Koch", Version:=2.0)>
Public Class ThirdClass
End Class
Class TestAuthorAttribute
Sub Main()
PrintAuthorInfo(GetType(FirstClass))
PrintAuthorInfo(GetType(SecondClass))
PrintAuthorInfo(GetType(ThirdClass))
End Sub
Private Shared Sub PrintAuthorInfo(ByVal t As System.Type)
System.Console.WriteLine("Author information for {0}", t)
' Using reflection
Dim attrs() As System.Attribute = System.Attribute.GetCustomAttributes(t)
' Displaying output
For Each attr In attrs
Dim a As Author = CType(attr, Author)
System.Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version)
Next
End Sub
' Output:
' Author information for FirstClass
' P. Ackerman, version 1.00
' Author information for SecondClass
' Author information for ThirdClass
' R. Koch, version 2.00
' P. Ackerman, version 1.00
End Class
こちらも参照ください
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET