An attribute (Attribute) is a declarative label for the behavior of various elements in a run-time delivery program, such as classes, methods, structures, enumerations, components, and so on, which can be used to represent additional information for assemblies, types, and various members within a type. You can add declarative information to a program by using attributes. A declarative label is described by placing brackets ([]) in front of the element to which it is applied. Typically, classes that represent attributes are derived from the System.Attribute class. Here are a few special features:
AttributeUsage pre-defined features
AttributeUsageDescribes how to use a custom attribute class. It specifies the type of project to which the attribute can be applied.
The syntax for this attribute is defined as follows:
[AttributeUsage( validon,allowmultiple=AllowMultiple,inherited =inherited)]
which
- The parameter Validon specifies the language element to which the attribute can be placed. It is a combination of the values of the enumerator AttributeTargets . The default value is AttributeTargets.All.
- The parameter allowmultiple(optional) provides a Boolean value for the AllowMultiple property of the attribute. If true, the attribute is multi-purpose. The default value is False (single).
- The Parameter inherited(optional) provides a Boolean value for the inherited property of the attribute. If true, the attribute can be inherited by a derived class. The default value is False (not inherited).
For example:
[AttributeUsage (attributetargets.class| Attributetargets.struct| Attributetargets.enum| attributetargets.delegate| AttributeTargets.Method| Attributetargets.property| Attributetargets.field| Attributetargets.constructor| attributetargets.event, allowmultiple=true, inherited=false)]
Then look at the following code:
[Serializable] publicclass A {}
From the above code, it can be seen that the SerializableAttribute feature will be applied to Class A, in C #, you can omit "Attribute", directly write "Serializable" can be. The prototype of the SerializableAttribute class is defined as follows:
[AttributeUsage (AttributeTargets.Class | attributetargets.struct | false)] [ComVisible (true)] Public Sealed class Serializableattribute:attribute {}
From the view of the definition of the SerializableAttribute class we also find that the attribute class can be attached to an attribute except from attribute, and the most used is the AttributeUsageAttribute attribute, which is defined as follows:
[Serializable] true)] [ComVisible (true)] Public Sealed class Attributeusageattribute:attribute {}
When defining the AttributeUsageAttribute class, it also attaches itself as an attribute of the class, which specifies the scope of application of the attribute class, represented by a AttributeTargets enumeration.
If the attribute has a constructor with parameters, you can wrap it with parentheses after the attribute and pass the argument. Of course, you can assign values to attributes or fields of an attribute class, or you can add multiple attributes at the same time.
Custom Attributes
Defining an attribute class is just like defining a normal class, you can declare a constructor, a field, a property, a method, and so on, or you can derive a subclass, but you must derive from a subclass of the System.Attribute class or System.Attribute.
For example:
[AttributeUsage (AttributeTargets.Class|AttributeTargets.Method|Attributetargets.property)] Public classMyattribute:attribute { Public stringTitle {Get;Set; } Public stringVerno {Get;Set; } } //attributes are used for classes[My (title="Draw", verno="1.0.2")] Public classDrawer {//Attributes are used for properties[My (Title ="Color", Verno ="1..0.2")] Public stringColor {Get;Set; } //attributes are used in methods[My (Title ="Color", Verno ="1.0.2")] Public voidDraw () {}//attributes are used for fields, compilation errors[My (Title ="Thick", Verno ="1.0.2")] Public intA; }
Note that when the MyAttribute attribute is used for a field, a compilation error occurs because the MyAttribute class has already indicated in the definition that it can only be used for classes, methods, properties, but does not indicate that it is available for the field.
By default, attributes are applied to objects that are more followed, and you can also apply attributes to the parameters in the method. As shown in the following code:
Public Static string Run ([in]string pt,[optional]int x) { returnstring . Empty; }
Apply the attribute order to the parameter before the parameter is placed. However, if you want to apply an attribute to the return value, is it possible to put the attribute before the return value? Just like this:
Public int Compute () {}
It is wrong to do this, the compilation cannot pass, then how to implement it?
As mentioned earlier, in the default case, the attribute is applied to the object following it, so, in many cases, the use of attributes will omit the keyword that represents the target of the attribute. The following is the full format when an attribute is applied to the target object:
[< target >:< feature list;]
The following lists the characteristics of the target keywords and related instructions:
Assembly: Indicates that the attribute will be applied to the current assembly, usually before the namespace or all type definitions in the assembly.
Module: for the current module.
Field: Used for the field, which can be omitted if the attribute is immediately followed by the field's declaration code.
Event: Used for events.
Method: Used for methods, and also for get and set accessors in properties.
PARAM: A parameter (value) in a set accessor in a parameter or property definition in a method.
Property: Used for attributes.
Type: Used for types.
Return: The return value of the get accessor in the property for the return value of the method.
With the introduction above, I believe you already know how to apply attributes to the return value of a method. The feature is applied to the method, and the target of the attribute is stated as return. As shown in the following code:
[return: MarshalAs (unmanagedtype.sysint)] Public int return 0; }
Retrieving features by Reflection technology
Here's how to find an attribute, which requires a reflection technique. As mentioned earlier, attributes can be understood as extended information attached to a type, and you can verify that the calling method of the code conforms to a specific requirement by locating the specified attribute in the type.
Let's look at an example:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 7 namespaceMy8 {9 [AttributeUsage (AttributeTargets.All)]Ten Public classTypeinfoattribute:attribute One { A Public stringDescription {Get;Set; } - } - the[TypeInfo (Description ="This is the enumeration type that we define. ")] - enumtestenum {one =1, both, three} - -[TypeInfo (Description ="This is a class that we define. ")] + Public classGoods {} - + class Program A { at Static voidMain (string[] args) - { - //Use the GetCustomAttributes method of the type class to get a list of attached attributes on the specified type - //returns an array of type object, with each element in the array representing an instance of an attribute class - //One of the overloads of the GetCustomAttributes method can pass a type as a parameter - //the type that represents the kind of attribute to get, and the TypeOf operator returns a type in //In this example we want to get a list of Typeinfoattribute features - //because the Testenum enumeration and the goods class are defined above, only one Typeinfoattribute attribute is applied to //so the number of elements in an array of attribute instances obtained is always 1 + - Object[] Attrs =typeof(Testenum). GetCustomAttributes (typeof(Typeinfoattribute),false); the if(Attrs. Length >0) * { $Typeinfoattribute ti = (typeinfoattribute) attrs[0];Panax NotoginsengConsole.WriteLine ("description Information for Testenum enumeration: {0}", ti. Description); - } the +Attrs =typeof(Goods). GetCustomAttributes (typeof(Typeinfoattribute),false); A if(Attrs. Length >0) the { +Typeinfoattribute ti = (typeinfoattribute) attrs[0]; -Console.WriteLine ("description information for the goods class: {0}", ti. Description); $ } $ - Console.read (); - } the } -}
Results:
Description of the Testenum enumeration: This is the enumeration type that we define.
Description information for the goods class: This is a class that we define.
Through the above introduction, I believe you have a certain understanding of the characteristics. Blog written here, I also do not wordy.
Attributes (C #)