The Visual Basic .NET Programming Language
< Day Day Up > |
The manner in which attributes are stored and retrieved is defined by the .NET Framework, so a detailed discussion is beyond the scope of this book. However, it is worth briefly discussing how attributes work, to give a better understanding about them. Take the following example. <System.AttributeUsage(System.AttributeTargets.All)> _ Public Class HelpAttribute Inherits Attribute Public ReadOnly Message As String Private _TopicNumber As Integer Public Property TopicNumber() As Integer Get Return _TopicNumber End Get Set (Value As Integer) _TopicNumber = Value End Set End Property Public Sub New(ByVal Message As String) Me.Message = Message End Sub End Class <Help("This is a test class.", TopicNumber := 5393)> _ Class Test End Class When the Test class is compiled, the values specified as the arguments to the Help attribute are serialized into a binary form that is stored with the Test class definition in the assembly. When a program asks for the attribute through reflection, the serialized attribute information is retrieved from the assembly. The method GetCustomAttributes on the class System.Type or on the class System.Reflection.Assembly can be used to retrieve attributes. This method returns an array of Object values that represent the custom attributes defined on the particular type or assembly. When the .NET Runtime builds the array of values, it takes each serialized attribute and then creates an instance of the attribute class, passing in the specified arguments and assigning the specified values to the fields and properties. The following example shows how the GetCustomAttributes method can be used to retrieve attributes at runtime. Imports System <AttributeUsage(AttributeTargets.All)> _ Public Class HelpAttribute Inherits Attribute Public ReadOnly Message As String Private _TopicNumber As Integer Public Property TopicNumber() As Integer Get Return _TopicNumber End Get Set (Value As Integer) _TopicNumber = Value End Set End Property Public Sub New(ByVal Message As String) Me.Message = Message End Sub End Class <Help("This is a test class.", TopicNumber := 5393)> _ Class Test End Class Module Main Sub Main() Dim T As Type = GetType(Test) Dim HelpAttribute As HelpAttribute HelpAttribute = CType(T.GetCustomAttributes(True)(0), _ HelpAttribute) Console.WriteLine(HelpAttribute.Message & ": " & _ HelpAttribute.TopicNumber) End Sub End Module This example fetches the first attribute that was applied to Test , casts it to a HelpAttribute , and then prints the value of the attribute. |
< Day Day Up > |