Attributes are about application’s metadata. Because of this, you can use Reflection for checking if a type recurs to custom
attributes and investigate metadata (that is, application information).
To accomplish this you invoke the System.Reflection.MemberInfo.GetCustomAttributes and System.Reflection.Attributes.GetCustomAttributes
shared methods. The first one returns all attributes applied to the
specified type whereas the second one returns an array of custom
attributes applied to an assembly, a type or its members, and method
parameters. The following is the most basic example for retrieving
information about attributes applied to members of the Document class:
'Requires an Imports System.Reflection directive
Public Sub GetMyAttributes()
'About members in the Document class
Dim info As System.Reflection.MemberInfo = GetType(Document)
'Retrieves an array of attributes
Dim attributesList() As Object = info.GetCustomAttributes(True)
'Enumerates applied attributes
For i As Integer = 0 To attributesList.Length - 1
Console.WriteLine(attributesList(i))
Next (i)
End Sub
The following example is
instead a little bit more complex and shows how you can perform actions
on each attribute instance through Attribute.GetCustomAttributes:
Public Sub GetMyAttributesComplex()
Dim typeToInvestigate As Type = GetType(Document)
' Get the type information for the DocumentName property.
Dim member_Info As PropertyInfo =
typeToInvestigate.GetProperty("DocumentName")
If Not (member_Info Is Nothing) Then
'Iterate through all the attributes of the property.
Dim attr As Attribute
For Each attr In Attribute.GetCustomAttributes(member_Info)
' Check for the DocumentPropertiesAttribute attribute.
If attr.GetType().
Equals(GetType(DocumentPropertiesAttribute)) Then
Console.WriteLine("Author: {0}", CType(attr,
DocumentPropertiesAttribute).Author)
'Additional ElseIf conditions here for other attributes..
End If
Next attr
End If
End Sub
In this particular scenario the code is used to iterate applied attributes.