Application of Attribute in .NET Programming (1)

zhaozj2021-02-11  187

Application of Attribute in .NET Program (1) Basic Concept of Attribute

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 usage method, special collection of several Attribute uses, provide you with reference.

Before the specific demo, I would like to introduce Attribute first. We know that there is a member of the Property member in the members of the class. 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: the public language is running to add a similar key to the description declaration, called Attribute, labeling the elements in the program, such as type, field, method And attributes, etc. The metadata of Attributes and Microsoft .NET Framework files are saved together, which can be used to describe your code when running, or affect the application's behavior when running.

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. Next, let's first look at the use of the properties in .NET, we will return to the head of Attribute later. (The code in the text uses C # written, but it also applies all .NET-based all languages)

Attribute as a compiler

There is a certain number of compilers instructions in C #, such as: #define debug, #undefine debug, #if, etc. These instructions are specialized to C # and are fixed in quantity. Attribute is used as a compiler instruction without quantity. 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 // Here define conditions

Using system;

Using system.Runtime.InteropServices;

Using system.diagnostics;

Namespace AttributeMo

{

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. The current time is" DateTime.now);

}

[Conditional ("Debug")]]

[Obsolete]

Private static void displaydebugmessage ()

{

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] is applied to the MessageBox function, [Conditional] applies to the DisplayRuntimeMessage method, [Obsolete] applied Go to the DisplayDebugMessage method.

Based on the three Attribute described above, we can guess the output when the program is running: DLLIMPORT Attribute indicates that MessageBox is a function in user32.dll so that we can call this function as internal method.

The important point is that Attribute is a class, so DLLIMPORT is also a class, and the Attribute class is instantiated when compiling, rather than being instantiated as usual classes. 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 of the parameters. If DEBUG is not defined, then the method will not be compiled. The reader can comment about the result of the #define debug and take a look at the result of the output (Release version, in the debug version Conditional debug Always set up). Obsolete indicates that the DispalyDebugMessage method is outdated, it has a better way to replace it, when our program calls a method of declaring Obsolete, then the compiler will give information, Obsolete has other two overloaded version. You can refer to the description of the ObsoleTeattribute class in MSDN.

Attribute class

In addition to those Attribute derived classes 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 derived from Attribute directly or indirectly, such as:

Public mycustomattribute: attribute {...}

Here, it is necessary to point out the naming specification of Attribute, which is your Attribute, the class name "Attribute". When your Attribute is applied to a program, the compiler first finds your Attribute, if not found Then it will find the definition of "Attribute Name" Attribute. 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. The code form is as follows: [AttriubTeusage] public custom attribute: attribute {...}

It is very interesting that Attributeusage itself is also an Attribute, which is an attribute applied to the Attribute class. AttributeUSage is naturally derived from Attribute, which has a parameter, this parameter is an enumeration type of AttributeTargets. Here is the definition of AttributeTargets:

Public Enum AttributeTargets

{

ALL = 16383,

AskSEMBLY = 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 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.

Use examples of AttributeUSAGE:

Using system;

Namespace Atttargscs

{

// This Attribute is only valid for classes.

[AttributeUsage (AttributeTargets.class)]

Public Class ClassTargettattribute: Attribute: Attribute

{

}

// The Attribute is only valid for the method.

[AttributeUSAG (AttributeTargets.method)]

Public Class methodTargettRibute: attribute {

}

// The Attribute is only valid for the constructor.

[AttributeUSAGE (AttributeTargets.constructor)]

Public Class ConstructOrgetAtttribute: Attribute

{

}

// The Attribute is only valid for the field.

[AttributeUSAGE (AttributeTargets.field)]

Public Class FieldTargettattribute: Attribute: Attribute

{

}

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

[AttributeUSAGE (AttributeTargets.class | attributeTargets.method)]

Public Class ClassMethodtargetAtttribute: Attribute

{

}

// The Attribute is valid for all elements.

[AttributeUSAGE (AttributeTargets.all)]

Public Class AllTargetsAttribute: Attribute: Attribute

{

}

/ / The usage of Attribute is applied to the program element.

[ClassTarget] // Application to the class

[ClassMethodTarget] // Application to the class

[Alltargets] // Application to class

Public Class TestClassAttribute

{

[ConstructOrget] // Application to the constructor

[AllTargets] // Application to the constructor

TestClassAttribute ()

{

}

[MethodTarget] // Application to Method

[ClassMethodTarget] // Application to Method

[AllTargets] // applied to method

Public void method1 ()

{

}

[FieldTarget] // Apply to the field

[AllTargets] // Application to 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 app, if it is just the content introduced, it is not enough to explain what is the practical value of Attribute, then we will introduce a few Attribute, which will introduce several Attribute, I believe you will have a new understanding of Attribute. (to be continued)

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

New Post(0)