Attributes

 <  Day Day Up  >  

The language defines keywords such as Public , ByRef , and Overridable that can be applied to declarations to modify their meaning. These predefined modifiers can be augmented by user -defined attributes that can store extra declarative information about types and type members . For example, attributes can be used to declare that a type or type member is obsolete and should no longer be used.

 <Obsolete("Use NewSquare class instead.")> _ Public Class Square   ... End Class Public Class NewSquare   ...   <Obsolete("Use NewMove method instead.")> _   Public Sub Move(ByVal x As Integer, ByVal y As Integer)     ...   End Sub   Public Sub NewMove(ByVal x As Integer, ByVal y As Integer, _       ByVal Refresh As Boolean)     ...   End Sub End Class 

Attributes are defined by declaring a class that inherits from the type System.Attribute . A System.AttributeUsageAttribute attribute must also be applied to the class. For example, the following type defines an Author attribute that can be used to name the author of a type.

 <AttributeUsage(AttributeTargets.All)> _ Class AuthorAttribute   Inherits Attribute   Public Name As String   Public Company As String   Public Sub New(ByVal Name As String)     Me.Name = Name   End Sub End Class 

The parameters to the constructor of a user-defined attribute define the arguments that must be supplied when the attribute is specified on a type or type member. Fields and properties in the user-defined attribute can also be assigned to. For example:

 <Author("John Doe", Company := "MegaCorp")> _ Module Test   <Author("Jane Doe", Company := "Acme")> _   Sub Main()   End Sub End Module 

To retrieve attributes, the Framework reflection classes can be used.

 <Author("John Doe", Company := "MegaCorp")> _ Class TestClass End Class Module Test   Sub Main()     Dim T As Type = GetType(TestClass)     Dim AuthAttribute As AuthorAttribute     AuthAttribute = CType(T.GetCustomAttributes(False)(0), _       AuthorAttribute)     Console.WriteLine(AuthAttribute.Name)     Console.WriteLine(AuthAttribute.Company)   End Sub End Module 
 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net