可以定义自定义属性并将其放入源代码,但如果没有某种方式检索这些信息并对其加以利用,那么这些属性的价值就会很小。 通过使用反射,可以检索使用自定义属性定义的信息。 键方法是 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