共用方式為


Examples of Custom Attribute Usage 

The following example defines a custom attribute that can be applied only to classes:

Example

<AttributeUsage(AttributeTargets.Class)> Public Class CustomAttribute
    Inherits System.Attribute

    'Declare two private fields to store the property values.
    Private m_LlabelValue As String
    Private m_VValueValue As Integer

    'The Sub New constructor is the only way to set the properties.
    Public Sub New(ByVal _Label As String, ByVal _Value As Integer)
        m_LlabelValue = _Label
        m_VValueValue = _Value
    End Sub

    Public Overridable ReadOnly Property Label() As String
        Get
            Return m_LlabelValue
        End Get
    End Property

    Public Overridable ReadOnly Property Value() As Integer
        Get
            Return m_VValueValue
        End Get
    End Property
End Class

Only the constructor for the attribute class can set the properties defined in this attribute. The following code shows how you could use the attribute:

' Apply the custom attribute to this class.
<Custom("Some metadata", 66)> Class ThisClass
    ' Add class members here.
End Class

See Also

Tasks

How to: Define Your Own Attributes
How to: Retrieve Custom Attributes

Reference

AttributeUsageAttribute

Concepts

Application of Attributes
Retrieving Information Stored in Attributes