Title | Make and use custom attributes in VB .NET |
Description | This example shows how to make and use custom attributes in VB .NET. |
Keywords | attribute, custom attribute |
Categories | VB.NET |
|
|
To create the custom attribute, make a class that inherits from System.Attribute. Use the AttributeUsage attribute to indicate the kinds of things that should be allowed to have the atribute. In this example, only classes are allowed to have the CustomClassAttribute. This class has a constructor that takes a string as a parameter and saves it in a private variable. Property procedures let you access the value later.
|
|
<AttributeUsage(AttributeTargets.Class)> _
Class CustomClassAttribute
Inherits System.Attribute
Private m_Value As String
Public Sub New(ByVal new_value As String)
m_Value = new_value
End Sub
Public Property Value() As String
Get
Return m_Value
End Get
Set(ByVal new_value As String)
m_Value = new_value
End Set
End Property
End Class
|
|
The following code uses the CustomClassAttribute. It declares the attribute on the Person class, passing its constructor the string "A Person." The GetCustomerClassAttribute function uses the GetCustomAttribute function to get a reference to the class's Attribute object of type CustomClassAttribute. It converts that into a CustomClassAttribute and uses its Value property procedure to return the string that was stored when the class was declared. The example program reads this value.
|
|
<CustomClassAttribute("A Person")> _
Public Class Person
Private m_FirstName As String
Private m_LastName As String
Public Property FirstName() As String
Get
Return m_FirstName
End Get
Set(ByVal Value As String)
m_FirstName = Value
End Set
End Property
Public Property LastName() As String
Get
Return m_LastName
End Get
Set(ByVal Value As String)
m_LastName = Value
End Set
End Property
Public Sub New(ByVal first_name As String, ByVal _
last_name As String)
m_FirstName = first_name
m_LastName = last_name
End Sub
Public Function GetCustomClassAttribute()
Dim attr As Attribute
attr = GetCustomAttribute( _
Me.GetType(), _
GetType(CustomClassAttribute), _
False)
Dim custom_class_attr As CustomClassAttribute = _
DirectCast(attr, CustomClassAttribute)
Return custom_class_attr.Value
End Function
End Class
|
|
This type of custom attribute might be used by some sort of tool into which objects of many different kids could be passed. You can use a custom attribute to determine whether an object is of a class that is marked in some special way.
|
|
|
|