Information Technology Reference
In-Depth Information
Restricting the Usage of an Attribute
You've seen that you can apply attributes to classes. But attributes themselves are classes, and
there is one important predefined attribute that you will often want to apply to your custom
attributes. It is the AttributeUsage attribute. You can use it to restrict the usage of an attribute
to a specific set of target types.
For example, if you want your custom attribute MyAttribute to be applied only to meth-
ods, you could use the following form of AttributeUsage .
Only to methods
[ AttributeUsage( AttributeTarget.Method ) ]
public sealed class MyAttributeAttribute : System.Attribute
{ ...
AttributeUsage has three important public properties, which are listed in Table 21-3. The
table shows the names of the properties and their meanings, as well as the default values of the
last two properties.
Table 21-3. Public Properties of AttributeUsage
Name
Meaning
Default
ValidOn
Stores a list of the types of targets to which the attribute can be
applied. The first parameter of the constructor must be an enum
value of type AttributeTarget .
Inherited
A Boolean value that specifies whether the attribute can be inherited
by derived classes of the decorated type.
true
AllowMultiple
A Boolean value that specifies whether the target can have multiple
instances of the attribute applied to it.
false
Search WWH ::




Custom Search