Information Technology Reference
In-Depth Information
The Constructor for AttributeUsage
The constructor for AttributeUsage takes a single, positional parameter that specifies which
target types are allowed for the attribute. It uses this parameter to set the ValidOn property. The
acceptable target types are members of the AttributeTarget enumeration. The complete set of
the members of the AttributeTarget enumeration is shown in Table 21-4.
You can combine the usage types by using the bitwise OR operator. For example, the
attribute declared in the following code can be applied only to methods and constructors.
Targets
[ AttributeUsage( AttributeTarget.Method | AttributeTarget.Constructor ) ]
public sealed class MyAttributeAttribute : System.Attribute
{ ...
Table 21-4. Members of Enum AttributeTarget
All
Assembly
Class
Constructor
Delegate
Enum
Event
Field
GenericParameter Interface
Method
Module
Parameter
Property
ReturnValue
Struct
When you apply AttributeUsage to an attribute declaration, the constructor will have at
least the one required parameter, which contains the target types to be stored in ValidOn . You
can also optionally set the Inherited and AllowMultiple properties by using named parame-
ters. If you do not set them, they will have their default values, as shown in Table 21-3.
As an example, the next code block specifies the following about MyAttribute :
￿ MyAttribute must be applied only to classes.
￿ MyAttribute is not inherited by classes derived from classes to which it is applied.
There cannot be multiple instances of MyAttribute applied to the same target.
￿
[ AttributeUsage( AttributeTarget.Class, // Required, positional
Inherited = false, // Optional, named
AllowMultiple = false ) ] // Optional, named
public sealed class MyAttributeAttribute : System.Attribute
{ ...
Search WWH ::




Custom Search