AttributeUsage
attributeThe AttributeUsage
attribute is used to describe how an attribute class can be used.
The AttributeUsage
attribute has a positional parameter named that enables an attribute class to specify the kinds of declarations on which it can be used. The example
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class SimpleAttribute: System.Attribute {}
defines an attribute class named SimpleAttribute
that can be placed on class-declarations and interface-declarations. The example
[Simple] class Class1 {…} [Simple] interface Interface1 {…}
shows several uses of the Simple
attribute. The attribute is defined with a class named SimpleAttribute
, but uses of this attribute may omit the Attribute
suffix, thus shortening the name to Simple
. The example above is semantically equivalent to the example
[SimpleAttribute] class Class1 {…} [SimpleAttribute] interface Interface1 {…}
The AttributeUsage
attribute has an AllowMultiple
named parameter that specifies whether the indicated attribute can be specified more than once for a given entity. An attribute that can be specified more than once on an entity is called a multi-use attribute class. An attribute that can be specified at most once on an entity is called a single-use attribute class.
The example
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class AuthorAttribute: System.Attribute { public AuthorAttribute(string value); public string Value { get {…} } }
defines a multi-use attribute class named AuthorAttribute
. The example
[Author("Brian Kernighan"), Author("Dennis Ritchie")] class Class1 {…}
shows a class declaration with two uses of the Author
attribute.