Understanding of Delegates in C #

Source: Internet
Author: User

Please note that this is just a little bit of a personal understanding of the delegate in C #, referring to some blogs, if something is wrong, please point out, thank you!

A delegate is a function pointer, which is an abstraction of a method that is an instance of a delegate. Delegation is the C # language of a hurdle, understand the delegation to be considered C # really into the door. Delegates are particularly popular in C #, and the most common example is the use of delegates for event listeners. When we click on a button above WinForm, the system responds, which is actually a delegate.

Why do you use a delegate? It's definitely not complicated for simple problems. We know that in program design, data structures and algorithms are very important, but in the actual development, we do not seem to use these things, this is because we are using high-level language, like Java, C # this kind of. These high-level languages have been designed to help us take these issues into account, so we don't feel the existence of algorithms and data structures. For the simplest example, the list, hshtable, and so on that we use most are the data structures that Java has helped define for us. The same is true for delegates. The existence of a delegate is essentially to decouple the code, enabling the code to be maintainable and extensible.

Let's take a click of a button and then trigger an event as an example to illustrate.

 Public void Btnconfirmonclick () {    Functiona ();    Functionb ();}

In the above code, when a button is clicked, it will take the initiative to call Functiona (); FUNCTIONB (); These two methods, this completes our task Ah. However, when the user needs to see the changes in the second three, the above code will be frequently changed, for example, to add a new Functionc (), so that the above code is a distance from the requirements of engineering practice. According to the requirements of 23 design principles, when the coupling of the code is too large, it is necessary to split the code, how to split it? is to introduce a new Class C, when the button is clicked, Btnconfirmonclick () This method to notify the class C,c again to call Functiona (); FUNCTIONB (); These methods, in fact, are commissioned design ideas.

The following is a code for a delegate.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedelegatetest{classProgram {Static voidMain (string[] args) {A A=NewA ();//Define Button Ab b=NewB (a);//Define Response Event BC c=NewC (a);//Defining response Events C//button A is clickedA.raise ("Click"); //Button A is double-clicked//a.raise ("Double-click"); //Button A is triple combo//A.fall ();Console.ReadLine (); //since B and C subscribe to the events of a, no code is required, and B and C act as agreed.         }    }    /// <summary>    ///button A click Delegate/// </summary>    /// <param name= "Hand" >Click : Click, double tap</param>     Public Delegate voidRaiseeventhandler (stringhand); /// <summary>    ///Button A is commissioned by three hits/// </summary>     Public Delegate voidFalleventhandler (); /// <summary>    ///Button A/// </summary>     Public classA {/// <summary>        ///button A Click event/// </summary>         Public EventRaiseeventhandler RaiseEvent; /// <summary>        ///Button A is triple combo event/// </summary>         Public EventFalleventhandler fallevent; /// <summary>        ///Click/// </summary>        /// <param name= "Hand" >hand: Click, double click</param>         Public voidRaise (stringhand) {Console.WriteLine ("button a{0} click", hand); //call a click event, pass in a click or double-click the hand as a parameter            if(RaiseEvent! =NULL) {RaiseEvent (hand); }        }        /// <summary>        ///be triple combo/// </summary>         Public voidFall () {Console.WriteLine ("Button A is triple combo"); //call by Triple combo event            if(Fallevent! =NULL) {fallevent (); }        }    }    /// <summary>    ///Responding to Event B/// </summary>     Public classB {a A;  PublicB (A a) { This. A =A; A.raiseevent+=NewRaiseeventhandler (a_raiseevent);//Subscribe to click eventsA.raiseevent + =NewRaiseeventhandler (a_raiseevent);//Subscribe to click eventsA.fallevent + =NewFalleventhandler (a_fallevent);//Subscribe to Triple combo event        }        /// <summary>        ///action when the button is clicked/// </summary>        /// <param name= "Hand" >If button A is clicked, the B attack</param>        voidA_raiseevent (stringhand) {            if(Hand. Equals ("Click") ) {Attack (); }        }        /// <summary>        ///action when the button is triple-hit/// </summary>        voida_fallevent () {Attack (); }        /// <summary>        ///Attack/// </summary>         Public voidAttack () {Console.WriteLine ("Response to Event B response"); }    }    /// <summary>    ///Response Event C/// </summary>     Public classC {a A;  PublicC (A a) { This. A =A; A.raiseevent+=NewRaiseeventhandler (a_raiseevent);//Subscribe to click eventsA.fallevent + =NewFalleventhandler (a_fallevent);//Subscribe to Triple combo event        }        /// <summary>        ///action when the button is clicked/// </summary>        /// <param name= "Hand" >If button A is double-clicked, the attack</param>        voidA_raiseevent (stringhand) {            if(Hand. Equals ("Double click") ) {Attack (); }        }        /// <summary>        ///action when the button is triple-hit/// </summary>        voida_fallevent () {Attack (); }        /// <summary>        ///Attack/// </summary>         Public voidAttack () {Console.WriteLine ("Responding to event C responses"); }    }}

Understanding of Delegates in C #

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.