以下类使用了一个固有属性(Serializable),以及一个通用的属性(Sample),代码段也包括了通用属性的定义:
<Serializable(), Sample("Attribute Sample")>
_
Public Class TestClass
End Class
Public Class SampleAttribute
Inherits System.Attribute
Private attValue As String
Public Sub New(ByVal Value As String)
attributeValue = Value
End Sub
Public Property attributeValue()
Get
Return
attValue
End Get
Set(ByVal Value)
attValue
= Value
End Set
End Property
End Class
为了确定一个类是否包含固有属性,可以使用类中的GetType方法。这将返回一个类型对象的引用。类型对象属性返回一个TypeAttributes对象,这一对象允许类之间的属性关联。以下代码说明了校验特定固有属性的过程:
Dim test As New TestClass()
Dim objectType As System.Type
objectType = test.GetType()
If (objectType.Attributes And _
Reflection.TypeAttributes.Serializable)
Then
Debug.WriteLine("Serializable")
End If
If (objectType.Attributes And Reflection.TypeAttributes.Public) Then
Debug.WriteLine("Public")
End If
If (objectType.Attributes And Reflection.TypeAttributes.Abstract) Then
Debug.WriteLine("Abstract")
End If
为了校验通用属性,使用GetCustomAttributes方法。它将返回对象的数组,这些数组代表所有类中的属性。每一属性的类型都被校验以确定它是否是合法的,如果是,属性将被传递到属性类型的变量,并在需要的时候被处理:
Dim test As New TestClass()
Dim objectType As System.Type
Dim customAttribute As Object
Dim sampleAttr As SampleAttribute
objectType = test.GetType()
For Each customAttribute In objectType.GetCustomAttributes(False)
If TypeOf (customAttribute) Is SampleAttribute Then
sampleAttr = customAttribute
Debug.WriteLine(sampleAttr.attributeValue)
End If
Next