Basic concepts of Attribute
Some people often ask, what is Attribute? What is its use? It seems that this program can run without it. In fact. in Net, Attribute is a very important component. In order to help you understand and master Attribute and its usage, we have collected several examples of using Attribute for your reference.
Before a specific demonstration, I would like to give a general introduction to Attribute. We know that there are property members in the class, and both of them are interpreted in Chinese. Are they the same thing? From the code perspective, there are obvious differences. First, they have different positions in the code, and second, they are written differently (Attribute must be written in a pair of square characters ).
What is atrri.pdf
First, we are sure that Attribute is a class. The following is the description of this class in the msdn document:
When running in a common language, you can add a keyword-like description declaration called attributes, which marks elements in a program, such as types, fields, methods, and attributes. The metadata of the Attributes and Microsoft. NET Framework files is stored together and can be used to describe your code to the runtime, or affect the behavior of the application when the program is running.
In. NET, Attribute is used to deal with a variety of problems, such as serialization, program security features, prevent instant compilers from optimizing program code so that code can be easily debugged. Next, let's take a look at the use of several standard attributes in. NET. We will go back and discuss the Attribute class itself later. (The code in this article is written in C #, but it also applies to all. NET-based languages)
Attribute is the instruction of the compiler.
A certain number of compiler commands exist in C #, such as # define DEBUG, # undefine DEBUG, and # if. These commands belong to C # And are fixed in quantity. Attribute is used as a compiler instruction without limit. For example, the following three attributes:
- Conditional: it is used for Conditional compilation. Only when conditions are met can the compiler compile its code. It is generally used for program debugging.
- DllImport: used to mark non-. NET functions, indicating that this method is defined in an external DLL.
- Obsolete: This attribute is used to mark that the current method has been discarded and is no longer used.
The following code demonstrates the use of the preceding three attributes:
# Define DEBUG // define the condition using System; using System. runtime. interopServices; using System. diagnostics; namespace AttributeDemo {class MainProgramClass {[DllImport ("User32.dll")] public static extern int MessageBox (int hParent, string Message, string Caption, int Type ); static void Main (string [] args) {DisplayRunningMessage (); DisplayDebugMessage (); MessageBox (0, "Hello", "Message", 0); Console. readLine ( );} [Conditional ("DEBUG")] private static void DisplayRunningMessage () {Console. WriteLine ("start to run the Main subroutine. The current time is "+ DateTime. now);} [Conditional ("DEBUG")] [Obsolete] private static void DisplayDebugMessage () {Console. writeLine ("START Main subroutine ");}}}
If an Attribute is declared before a program element, this Attribute is applied to the element. The previous Code [DllImport] is applied to the MessageBox function, [Conditional] applies to the DisplayRuntimeMessage method and DisplayDebugMessage method, and [Obsolete] applies to the DisplayDebugMessage method.
According to the description of the three attributes mentioned above, we can guess the output generated when the program is running: DllImport Attribute indicates that MessageBox is a function in User32.DLL, in this way, we can call this function like an internal method.
The important thing is that Attribute is a class, so DllImport is also a class. Attribute classes are instantiated during compilation, rather than being instantiated at runtime as a common class. During Attribute instantiation, parameters can be included or not included according to the design of this Attribute class. For example, DllImport has parameters of "User32.dll. Conditional compiles the code that meets the definition conditions of the parameter. If DEBUG is not defined, this method will not be compiled, you can comment out the # define DEBUG line to see the output result (release version, Conditional Debug is always true in the debug version ). Obsolete indicates that the DispalyDebugMessage method is outdated and has a better method to replace it. When our program calls a method that declares the Obsolete, the compiler will provide information, there are two other versions of the Obsolete overload. You can refer to the description of the ObsoleteAttribute class in msdn.
Attribute Class
Apart from the Attribute Derived classes provided by. NET, we can customize our own attributes. All custom attributes must be derived from the Attribute class. Now let's take a look at the details of the Attribute class:
Protected Attribute (): a protected constructor, which can only be called by the derived class of Attribute.
Three static methods:
Static Attribute getcustomattri (): This method has eight overloaded versions, which are used to retrieve attributes of the specified type applied to class members.
Static Attribute [] GetCustomAttributes (): This method has 16 overloaded versions used to retrieve Attribute arrays of the specified type applied to class members.
Static bool IsDefined (): it consists of eight overloaded versions to check whether the custom attribute of the specified type is applied to the members of the class.
Instance method:
Bool IsDefaultAttribute (): If the Attribute value is the default value, true is returned.
Bool Match (): indicates whether the Attribute instance is equal to a specified object.
Public Attribute: TypeId: gets a unique identifier, which is used to distinguish different instances of the same Attribute.
We briefly introduced the methods and attributes of the Attribute class, and some of them are inherited from the object. It is not listed here.
The following describes how to customize an Attribute: customizing an Attribute does not require special knowledge, but is similar to writing a class. The custom Attribute must be derived directly or indirectly from the Attribute class, for example:
Public MyCustomAttribute: Attribute {...}
Here, we need to point out the Attribute naming rules, that is, your Attribute class name + "Attribute". When your Attribute is applied to an element of a program, the compiler first looks for the definition of your Attribute. If not, it will look for the definition of "Attribute name" + Attribute. If none of them are found, the compiler reports an error.
For a custom Attribute, you can use the Attribute of AttributeUsage to limit the type of the element applied by your Attribute. The code format is as follows: [AttriubteUsage (parameter setting)] public custom Attribute: Attribute {...}
It is very interesting that AttributeUsage itself is also an Attribute, which is specially applied to the Attribute class. attributeUsage is also derived from Attribute. It has a constructor with parameters. This parameter is an enumeration type of AttributeTargets. The following is the definition of AttributeTargets:
public enum AttributeTargets{ All=16383, Assembly=1, Module=2, Class=4, Struct=8, Enum=16, Constructor=32, Method=64, Property=128, Field=256, Event=512, Interface=1024, Parameter=2048, Delegate=4096, ReturnValue=8192}
The value of AttributeTarges, as a parameter, can be combined using the "or" operation. If you do not specify a parameter, the default parameter is All. In addition to inheriting the methods and attributes of Attribute, AttributeUsage also defines the following three attributes:
AllowMultiple: read or set this Attribute to indicate whether multiple attributes can be applied to a program element.
Inherited: read or set this Attribute to indicate whether the applied Attribute can be Inherited or overloaded by the derived class.
ValidOn: read or set this Attribute to indicate the type of the element that Attribute can be applied.
AttributeUsage example:
Using System; namespace AttTargsCS {// This Attribute is only valid for the class. [AttributeUsage (AttributeTargets. class)] public class ClassTargetAttribute: Attribute {} // This Attribute is only valid for methods. [AttributeUsage (AttributeTargets. method)] public class MethodTargetAttribute: Attribute {} // This Attribute is only valid for the constructor. [AttributeUsage (AttributeTargets. constructor)] public class ConstructorTargetAttribute: Attribute {} // This Attribute is only valid for fields. [AttributeUsage (AttributeTargets. field)] public class FieldTargetAttribute: Attribute {} // This Attribute is valid for classes or methods (combinations ). [AttributeUsage (AttributeTargets. class | AttributeTargets. method)] public class ClassMethodTargetAttribute: Attribute {} // This Attribute is valid for all elements. [AttributeUsage (AttributeTargets. all)] public class AllTargetsAttribute: attribute {} // usage of Attribute defined above applied to program elements [ClassTarget] // applied to class [ClassMethodTarget] // applied to class [AllTargets] // applied to class public class TestClassAttribute {[ConstructorTarget] // apply to the constructor [AllTargets] // apply to the constructor TestClassAttribute () {} [MethodTarget] // apply to method [ClassMethodTa