如果您可以定義自定義屬性並將它們放入原始程式碼,但沒有辦法擷取那些資訊並對其採取行動,這樣的事實就沒有太大的價值。 藉由使用反映,您可以擷取以自定義屬性定義的資訊。 關鍵方法是 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