Delegation in. net

Source: Internet
Author: User
ArticleDirectory
    • Finally, click the following green channel-Follow debuglzq to share progress ~

Advanced features in. net, such as delegation, events, reflection, and features, are often used to master and master these features. netProgramEvaluation criteria from entry level to intermediate level. In this article, debuglzq describes how the Delegate Feature in. NET is implemented in the. NET Framework. For example, the topic of this article is about the nature of delegate in. net.

Delegation is not unfamiliar to programmers who have C ++ programming experience. function pointers in C ++ are indeed very similar to delegation. Many people like it. the delegate in. NET is called a "safe function pointer ". Debuglzq does not argue that this method is correct, but the delegate does implement a function that is very similar to the function pointer, that is, the mechanism of the method specified by the program callback.

1. Basic principles of delegation

The delegate contains a pointer to a method. At this point, the delegate implementation mechanism is exactly the same as the C ++ function pointer. The reason for the security of delegation is that the delegation and others.. NET members are of the same type. Any delegate object is system. an object of a derived class of delegate. shows the delegate class structure in the. NET Framework:

From this structure, we can see that any custom delegate inherits from the parent class system. Delegate. This class defines most of the delegate features, and the features of system. multicastdelegate will be introduced later.

The following is a specific example,CodeAs follows:

 Using System;  Namespace  Delegate nature {  Class  Program {  ///   <Summary>          ///  Debuglzq resolution delegate  ///  Define delegation.  ///   </Summary>          ///   <Param name = "I">  Accept an integer Parameter </I>          Public   Delegate   Void Testdelegate ( Int  I );  Static   Void Main ( String  [] ARGs ){  //  Call the delegate Method Testdelegate d = New  Testdelegate (printmessage1); D ( 0  ); D (  1  ); Console. Read ();}  ///   <Summary>          ///  A static method that complies with testdelegate's definition  ///   </Summary>          ///   <Param name = "I">  Integer Parameter  </Param>          Static  Void Printmessage1 ( Int  I) {console. writeline (  "  The  " + I + "  Methods  "  );}}} 

In the code above, first define a new type named testdeletate through public delegate void testdelegate (int I); which is inherited from system. muticastdelegate. AndIt will containInvokeMethod. This method accepts an integer parameter and does not return a value. These steps are automatically completed by the C # compiler.
Then declare a testdelegate Object D and bind a static method void printmessage1 to the delegate. Note that the delegate can accept the instance method or static method. The difference is described below. Finally, it is also an expected part. D is called for execution:D (0), D (1); you may be confused here. In fact, this is just a syntax designed by the C # designer to simplify the input of programmers.In essence, a delegate call is an invoke method generated when the delegate is defined.

For ease of understanding, we can fully write the call part of the delegate as follows:

 
D. Invoke (0); D. Invoke (1);

When the delegate is executed,. Net checks the delegate object and finds the printmessage1 (int I) method, then passes the parameter to the method and runs it.

The following is the running result of the program:

Summary: delegation is a type that inherits from system. Delegate. Each delegate object contains at least one pointer to a method. This method can be an instance method or a static method. The delegate implements the callback method mechanism to help programmers design object-oriented programs in a more concise and elegant manner.

2. Internal Structure of the Delegate

To further clarify the nature of delegation, we will introduce the internal structure of delegation. Next, let's take a look at the structure of system. Delegate, as shown in:

_ Target is a reference to the target instance. When an instance method is bound to a delegate, this parameter is set to an instance object of the type of the method. When a static method is bound to the delegate, this parameter is set to null. (The essential difference between the delegate callback instance method and the static method is that !)

_ Methodptr is a pointer to the binding method code. It is similar to the function pointer in C ++. The binding static methods or instance methods are not different in the settings of this Member.

In fact, for custom delegates inherited from system. muticastdelegate, there is another member variable: _ Prev, which points to the next delegate in the delegate chain. This will be introduced below.

3. [Chain delegation]

A delegated chain is a linked list composed of delegates, rather than a new one. The figure in Figure 1 shows that all custom delegates are directly integrated with the system. multicastdelegate type, which is designed for the delegate chain.

To thoroughly understand the implementation mechanism of chained delegation, it is necessary to take a look at the internal members of system. multicastdelegate, as shown in three important members:

System. two internal members of Delegate, system. multicastdelegate inherits the two members and adds a _ Prev Member, which is a referenced variable of the Delegate. When a delegate is concatenated to the end of the current delegate, this member will be set to point to the subsequent delegate instance object.. . Net.

Debuglzq emphasizes that chained delegation refers to a linked list of delegates rather than another type of special delegation. When a method on the execution chain is executed, subsequent delegation will be executed accordingly. How to change the execution sequence is described later. System. muticastdelegate defines the support for chain delegation. On the basis of system. Delegate, it adds a pointer to the subsequent delegate, thus implementing a simple linked list structure.

For a deeper understanding of chained delegation, the following is an example of chained delegation: 

 Using  System;  Using  System. Collections. Generic;  Using  System. LINQ; Using  System. text;  Namespace  Chain delegate {  Class  Program {  ///   <Summary>          ///  Defined delegation.  ///   </Summary>          Public   Delegate   Void  Testmultidelegate (); Static   Void Main ( String  [] ARGs ){  //  Declare a delegate variable and bind the first method Testmultidelegate handler = New  Testmultidelegate (printmessage1 );  //  Bind the second method Handler + = New  Testmultidelegate (printmessage2 );  // Bind the third method Handler + = New  Testmultidelegate (printmessage3 );  //  Check Result  Handler (); console. Read ();}  Static   Void  Printmessage1 () {console. writeline (  "  First Method  "  );}  Static  Void  Printmessage2 () {console. writeline (  "  Method 2  "  );}  Static   Void  Printmessage3 () {console. writeline (  "  Third Method  "  );}}} 

Do not explain the above Code too much. To facilitate understanding, rewrite the core part of the above Code in a complicated way:

Testmultidelegate handler =NewTestmultidelegate (printmessage1); testmultidelegate handler2=NewTestmultidelegate (printmessage2); testmultidelegate handler3=NewTestmultidelegate (printmessage3); testmultidelegate handlerhead= Handler + handler2 +Handler3; handlerhead. Invoke ();

In fact, the two writing methods are essentially the same, but the first one is more concise and general.
The program output is as follows:

The result shows that when the program calls the chain head handlerhead of the delegate chain, all the delegate methods after the delegate are called accordingly.

We may try to change the handlerhead call to the following code:

 
Handler ();

After execution, the execution result is exactly the same as before replacement. In fact, the above Code does not assign any delegated instance to handlerhead. Instead, it only Concatenates the delegated instances in all counties and allows handlerhead to reference the delegated chain, therefore, handlerhead and handler actually reference the same delegate instance.

4. Description

The execution sequence of chained delegation is as follows: Execute sequentially from the current delegate according to the vinegar on the delegated chain. If necessary, use getinvocationlist () methods To obtain all the delegates to be executed on the delegate chain, and execute them (invoke) in any desired order.

A delegate can be a method with a return value, but when a method with a return value is added to the delegate chain, the programmer needs to manually call each method on the delegate chain, otherwise, the delegated user intelligently obtains the return value of the last executed method on the delegated chain.

The delegated application usually involves the executor of a task to reallocate the detailed work. The executor knows exactly what work is going to be executed, but delegates the execution details to other components, methods, or assembly.

5. Conclusion This article aims to clarify the delegation in. net. You may be welcomed to criticize and correct the mistakes!
Today is Valentine's Day on the Chinese Valentine's Day. I would like to pay tribute to the programmers who are still working on the front-line. I wish you a better half as soon as possible! Finally, click the following green channel-Follow debuglzq to share progress ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.