C # delegation and delegation chain,
Delegation is an important feature of c. The Code is as follows:
Class Program {public delegate void DelegateTest (); static void Main (string [] args) {DelegateTest dtstatic = new DelegateTest (Program. method1); // instantiation, static method, no new DelegateTest dtinstance = new DelegateTest (new Program (). method2); // instance method, which requires new DelegateTest delegatechain = null; // The delegation Chain Defined as null delegatechain + = dtinstance; // use "+" to add the delegated instance delegatechain + = dtstatic; // delegatechain (); Console. read ();} private static void method1 () {Console. writeLine ("static method output");} private void method2 () {Console. writeLine ("instance method output ");}}
The running result is as follows:
From the results, we can see that the execution sequence of the delegate chain is the order in which the delegated instance is added;
Similarly, you can also use "-" to remove the delegated instance from the delegated chain:
Class Program {public delegate void DelegateTest (); static void Main (string [] args) {DelegateTest dtstatic = new DelegateTest (Program. method1); // instantiation, static method, no new DelegateTest dtinstance = new DelegateTest (new Program (). method2); // instance method, which requires new DelegateTest delegatechain = null; // The delegation Chain Defined as null delegatechain + = dtinstance; // use "+" to add the delegated instance delegatechain + = dtstatic; delegatechain-= dtstatic; // use "-" to remove the delegated instance delegatechain (); Console. read ();} private static void method1 () {Console. writeLine ("static method output");} private void method2 () {Console. writeLine ("instance method output ");}
The running result is as follows: