Initial knowledge of C # delegation and entrust chain

Source: Internet
Author: User

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

Related Article

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.