Delegates are a very important feature of C #. The code is as follows:
classProgram { Public Delegate voiddelegatetest (); Static voidMain (string[] args) {delegatetest dtstatic=NewDelegateTest (PROGRAM.METHOD1);//instantiation, static method, without newDelegateTest dtinstance =NewDelegateTest (NewProgram (). Method2);//instance method, need newDelegateTest Delegatechain =NULL;//A delegate chain that is defined as nullDelegatechain + = dtinstance;//add a delegate instance with "+"Delegatechain + = dtstatic;//Delegatechain (); Console.read (); } Private Static voidmethod1 () {Console.WriteLine ("static method Output"); } Private voidMethod2 () {Console.WriteLine ("instance method Output"); } }
The results of the operation are as follows:
From the results, we can see that the order of execution of the delegate chain is the order of the delegate instance;
Similarly, you can also use "-" to remove a delegate instance in a delegate chain:
classProgram { Public Delegate voiddelegatetest (); Static voidMain (string[] args) {delegatetest dtstatic=NewDelegateTest (PROGRAM.METHOD1);//instantiation, static method, without newDelegateTest dtinstance =NewDelegateTest (NewProgram (). Method2);//instance method, need newDelegateTest Delegatechain =NULL;//A delegate chain that is defined as nullDelegatechain + = dtinstance;//add a delegate instance with "+"Delegatechain + =dtstatic; Delegatechain-= dtstatic;//remove a delegate instance with "-"Delegatechain (); Console.read (); } Private Static voidmethod1 () {Console.WriteLine ("static method Output"); } Private voidMethod2 () {Console.WriteLine ("instance method Output"); }
The results of the operation are as follows:
Initial knowledge of C # delegation and entrust chain