Analyze problems
In the previous article, I have introduced in detail the basic concepts of delegation. The so-called chain delegate is a linked list composed of delegates. All custom delegates are directly inherited from the system. multicastdelegate type. This type is designed for chained delegation. Therefore, all custom delegates have the ability to become a chain delegate. When more than one delegate is linked together to form a delegate chain, the delegate of the call header will cause all the delegate methods on the chain to be executed.
Now let's look at a practical example, as shown in the following code:
Using system; namespace test {class multicastdelegate {/// <summary> // defined delegate /// </Summary> Public Delegate void testmulticastdelegate (); static void main () {// declare a delegate variable and bind the first method testmulticastdelegate handler = new testmulticastdelegate (printmessage1); // bind the second method handler + = new testmulticastdelegate (printmessage2 ); // bind the third method handler + = new testmulticastdelegate (printmessage3); // check the result handler (); console. read ();} static void printmessage1 () {console. writeline ("1st methods");} static void printmessage2 () {console. writeline ("2nd methods");} static void printmessage3 () {console. writeline ("3rd methods ");}}}
In this example, the above Code first defines a Commission testmulticastdelegate without returning any parameters. In the main function, it declares the delegate variable handler of testmulticastdelegate and binds the first method printmessage1. Then, the second delegate is initialized through handler + = new testmulticastdelegate (printmessage2); at the same time, printmessage2 is bound and the second delegate is attached after the first delegate. Then, attach the third delegate and bind it to printmessage3. This is a simple and clear method. Readers with experience in interface design may be familiar with this method. When developing an Asp.net or Windows application, when adding a button event, visual Studio generates similar code for us.
Note:
Here I emphasize again that chain delegation refers to a delegate linked list, rather than another special type of delegation. When a method on the execution chain is executed, the subsequent delegate methods will be executed in sequence. System. multicastdelegate defines the support for chain delegation. In system. based on the delegate, it adds a pointer to the subsequent delegate, so as to implement a simple linked list structure. the multicastdelegate structure will be covered in subsequent sections of this chapter.
Answer
A chain delegate is a linked list composed of delegates. When a delegate on a linked list is called back, subsequent delegates on all linked lists will be executed sequentially.
What is chain delegate