Application of Attribute in .NET Programming (1)

xiaoxiao2021-03-06  159

Attribute's basic concept Niwalker (original)

I often have a friend asking, what is Attribute? what's it for? It seems that this Dongdong program can also run. In actually in .NET, Attribute is a very important part.

In order to help you understand and master Attribute, and its method, special collections of several Attribute use, provide you with reference. Before the specific demo, I would like to introduce Attribute first. We know that there is a Property member in the members of the class, both in Chinese are interpreted, then they are not

Is it the same thing? From the code, it is obviously different, first of all, their position is different in the code, followed by the different ways (Attribute must be written in a pair of squares).

What is Atribute First, we affirm that Attribute is a class. The following is the description of the MSDN document on it: the public language is running, allowing you to add a similar key description declaration called Attribute, which labels the elements in the program, such as types, Fields, methods, and attributes, etc.

The metadata of Attributes and Microsoft .NET Framework files are saved together, you can use to describe your code to runtime, or affect the application when running

behavior.

In .NET, Attribute is used to handle multiple problems, such as serialization, security features, to prevent the instant compiler from optimizing the program code to easily debug, etc. the following

Let's first look at the use of the properties in .NET, let's go back to discuss Attribute this class itself later. (The code in the text uses C # writing, but the same foundation

All languages ​​for .NET)

Attribute is a quantity compiler instruction in C # as a compiler, such as: #define debug, #undefine debug, #if, etc. These instructions are specialized to C # and are fixed in quantity. and

Attribute is used as a compiler instruction from being limited. For example, the three attributes below:

Conditional: The role of conditional compilation, only satisfying the condition, allowing the compiler to compile its code. Generally used during program debugging. DLLIMPORT: The function used to mark non-.NET indicates that the method is defined in an external DLL. Obsolete: This property is used to mark the current method has been discarded and no longer used. The following code demonstrates the use of the above three properties:

#define DEBUG // herein defined conditions 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 running the main subroutine. Current time is" DateTime.now); () {Console.WriteLine ("Start Main Subprogram");}}} If an attribute is declared in front of a program element, then this Attribute is applied to the element, the previous code, [DLLIMPORT] applied to MessageBox function

On, [Conditional] is applied to the DisplayRuntimeMessage method and the DisplayDebugMessage method, [OBSOLETE] is applied to the DisplayDebugMessage method.

According to the three Attribute described above, we can guess the output when the program is running: DLLIMPORT Attribute indicates that MessageBox is User32.dll

The function, so we can call this function as an internal method.

Important is that Attribute is a class, so DLLIMPORT is also a class, and the Attribute class is instantiated when compiling, not like the usual class.

Waiting instantiation. When Attribute is instantiated, according to the design of the Attribute class, you can use parameters, or without parameters, such as DLLIMPORT with "user32.dll" parameters.

Conditional compiles the code that meets the definition conditions of the parameters. If you do not define Debug, then the method will not be compiled. The reader can comment down #define debug.

The result of the output (Release version is always established in the Debug version). Obsolete shows that the DispalydebugMessage method is outdated, it has one

A better way to replace it, when our program calls a method that declares Obsolete, the compiler will give information, and Obsolete has other two overloaded versions. everyone

You can refer to the description of the ObsoleTeattribute class in the MSDN.

In addition to the Attribute derived class provided by .NET, we can customize our own Attribute, 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 (): Protected constructor can only be called by Attribute derived class.

Three static methods:

Static Attribute getCustomAttribute (): This method has 8 overloaded versions, which are used to remove Attribute applied to the specified type on the class member.

Static Attribute [] getCustomAttributes (): This method has 16 overload versions to remove the Attribute array that applies the specified type on the class member.

Static Bool IsDefined (): From eight overload versions, see whether or not to specify custom Attributes are applied to the members of the class.

Example method:

Bool isdefaultAttRibute (): If the value of Attribute is the default value, then Return true.

Bool match (): Indicates whether this Attribute instance is equal to a specified object.

Public property: TYPEID: Get a unique identifier that is used to distinguish between different instances of the same Attribute.

We simply introduce the method and properties of the Attribute class, and some are inherited from Object. It is not listed here.

The following describes how to customize an attribute: Customize an Attribute does not require special knowledge, in fact, and write a class. Custom attribute must be directly or

Indirectly derived from Attribute, such as:

Public mycustomattribute: attribute {...}

Here, it is necessary to point out the naming specification of Attribute, which is your Attribute, class name "attribute", compiles when your Attribute is applied to an element of a program

Find your Attribute definition first, if you don't find it, then it will find the "Attribute Name" Attribute definition. If you have not found it, then the compiler is wrong.

For a custom Attribute, you can define the type of element applied by Attributeusage at attributeusage at the AttributeUSage atTribute. The code form is as follows:

[AttriubTeusage] PUBLIC Customized Attribute: attribute {...}

Very interesting, Attributeusage itself is also an Attribute, which is specially applied at the Attribute class. Attributeusage is naturally from Attribute

Delivery, it has a parameter constructor, this parameter is an enumeration type of AttributeTargets. Here 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 AttributeTarge as parameters allows multiple worth combinations to be permitted via "or", if you do not specify parameters, then the default parameter is all. In addition to inheriting Attribute, AttributeUsage defines the following three properties:

ALOWMULTIPLE: Reads or sets this property, indicating whether multiple Attributes can be applied to a program element.

Inherited: Read or set this property, indicating whether the Attribute that is applied can be derived or overloaded.

Validon: Reads or sets this property, indicating the type of Elements that Attribute can be applied.

ATTRIBUTEUSAGE Usage: use system; namespace atttargscs {

// This Attribute is only valid for classes. [AttributeUSAGETS.CLASS] PUBLIC CLASS CLASSTARGETATTRIBUTE: Attribute {}

// The Attribute is only valid for the method. [AttributeUSAGETS.METHOD] Public Class methodTargettRibute: attribute {}

// The Attribute is only valid for the constructor. [AttributeUSAGE (AttributeTargets.constructor)] Public Class ConstructionORTARGETATTRIBUTE: Attribute {}

// This Attribute is only valid for the field. [AttributeUSAGETS.FIELD] Public Class FieldTargettattribute: attribute {}

// This Attribute is valid (combined) on class or method (combined).

// This Attribute is valid for all elements. [AttributeUSAGETS.ALL] Public Class AllTargetsAttribute: attribute {}

/ / ATtribute is applied to the usage [ClassTarget] // applied to the class [ClassMethodTarget] // applied to class [alltargets] // applied to class public class testclassattribute {[constructOrget] // applied to the constructor [AllTargets] // Appliance TestClassAttribute () {} [MethodTarget] // Apply to Method [ClassMethodTarget] // Apply to Method [AllTargets] // Application to Method PUBLIC VOID METHOD1 () {} [FieldTarget] // Apply to the field [AllTargets] // applied to the field public int myint;

Static void main (string [] args) {}}}

At this point, we introduced the Attribute class and their code format. You must know how to use Attribute in your application, if you just introduce the content

It is still not enough to explain what practical value of Attribute, then start from the later chapter, we will introduce several Attribute, I believe you will have attribute.

A new understanding.

转载请注明原文地址:https://www.9cbs.com/read-127987.html

New Post(0)