The Visual Basic .NET Programming Language
< Day Day Up > |
Attribute classes define attributes that can be applied to declarations. Attribute classes always inherit from the class System.Attribute , and by convention the name of the attribute class should end in the word "Attribute." (For example, if you wanted to define a Help attribute, the name of the class would be HelpAttribute .)
An attribute class must also have a System.AttributeUsageAttribute attribute applied to it. The ValidOn parameter of the AttributeUsage constructor specifies what kinds of declarations the attribute may be placed on and whether the attribute is multiuse and/or inherited. Table 15-1 lists the types of declarations that attributes may be placed on and the corresponding values that can be passed to the ValidOn parameter.
The parameters of an attribute are defined by the parameters of the instance constructors of the attribute. The following example defines an attribute that can take either a String value or a String value and an Integer value as arguments, and shows a use of the attribute. <System.AttributeUsage(System.AttributeTargets.All)> _ Public Class HelpAttribute Inherits Attribute Public ReadOnly Message As String Public ReadOnly TopicNumber As Integer Public Sub New(ByVal Message As String) Me.Message = Message End Sub Public Sub New(ByVal Message As String, ByVal TopicNumber As Integer) Me.Message = Message Me.TopicNumber = TopicNumber End Sub End Class <Help("This is a test class.", 5393)> _ Class Test End Class Table 15-1. AttributeTargets Values
Attribute properties represent optional values for the attribute and are defined by instance fields and properties in the attribute class. To be used when an attribute is applied, the field or property cannot be ReadOnly . The following example rewrites the previous example using a property for the TopicNumber instead of constructor arguments. <System.AttributeUsage(System.AttributeTargets.All)> _ Public Class HelpAttribute Inherits Attribute Public ReadOnly Message As String Private _TopicNumber As Integer Public Property TopicNumber() As Integer Get Return _TopicNumber End Get Set (Value As Integer) _TopicNumber = Value End Set End Property Public Sub New(ByVal Message As String) Me.Message = Message End Sub End Class <Help("This is a test class.", TopicNumber := 5393)> _ Class Test End Class Only certain types can be stored in attributes. Fields, properties, and constructor arguments in an attribute class can only be one of the following types:
If a field, property, or constructor uses a type that isn't in this list (or if they use an enumeration that isn't accessible), the field, property, or constructor cannot be used when the attribute is applied to a declaration.
|
< Day Day Up > |