Dela via


Custom Attributes in Visual Basic

Custom attributes are user-defined attributes that provide additional information about program elements. For example, you might define a custom security attribute that specifies the permissions required by the caller to execute a procedure.

You define custom attributes in attribute classes based on the System.Attribute class. Attribute classes themselves use an attribute called AttributeUsageAttribute to provide information about how the attribute can be used. Specifying Inherited = True indicates that an attribute can propagate to derived classes. Setting the AllowMultiple property to True allows you to apply more than one instance of the attribute to a program element. The AttributeTargets enumeration lets you define which kinds of program elements your attribute can apply to.

In the following code, the AttributeUsageAttribute attribute specifies an attribute that can be applied to any type of item, inherited, and applied only once:

<AttributeUsage(AttributeTargets.All, Inherited:=True, AllowMultiple:=False)> _
Class TestAttribute1
    Inherits Attribute
End Class

You can use the Or operator to combine multiple items from the AttributeTargets enumeration, as in the following code:

<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method)> _
Class TestAttribute2
    Inherits Attribute
End Class

In This Section