Attribute Class represents the base class for custom attributes. : Attribute « Language Basics « VB.Net

Attribute Class represents the base class for custom attributes.


Imports System
Imports System.Reflection

Public Module CustomAttrVB
    Public Enum Employee
        A = 1
    End Enum

    <AttributeUsage(AttributeTargets.Method)> _
    Public Class EmployeeTypeAttribute
        Inherits Attribute
        Public Sub New(ByVal emp As Employee)
            Me.theEmp = emp
        End Sub
        Protected theEmp As Employee
        Public Property Pet() As Employee
                Return theEmp
            End Get
            Set(ByVal Value As Employee)
                theEmp = Value
            End Set
        End Property

    End Class

    Class EmployeeTypeTestClass

        <EmployeeType(Employee.A)> _
        Public Sub AMethod()
        End Sub

        <EmployeeType(Employee.B)> _
        Public Sub BMethod()
        End Sub

        <EmployeeType(Employee.C)> _
        Public Sub CMethod()
        End Sub
    End Class

    Sub Main()
        Dim testClass As New EmployeeTypeTestClass()
        Dim tcType As Type = testClass.GetType()
        Dim mInfo As MethodInfo
        For Each mInfo In tcType.GetMethods()
            Dim attr As Attribute
            For Each attr In Attribute.GetCustomAttributes(mInfo)
                If TypeOf attr Is EmployeeTypeAttribute Then
                    Dim attrCustom As EmployeeTypeAttribute = CType(attr, EmployeeTypeAttribute)
                    Console.WriteLine("Method {0} has a pet {1} attribute.",mInfo.Name(), attrCustom.Pet.ToString())
                End If
    End Sub
End Module


Related examples in the same category

1.Obsolete attribute
2.Define and use Attribute to track bugsDefine and use Attribute to track bugs