. NET Learning delegates and events

Source: Internet
Author: User

1. What is a delegate
In layman's words: a delegate is a container that can store pointers to methods that conform to a format (method signature)
Upload Image:

2. Delegate syntax
Prepare a method: String Hello (String userName) {}
String Hello2 (String userName) {}
Declaring a delegate class: Delegate string Dgsayhi (string userName);
Create delegate object: Dgsayhi Dgsay = new Dgsayhi (Hello);
or dgssyhi Dgsay = Hello;
Additional method: Dgsay+=hello2;
Delete method: Dgsay-=hello2;
Call Delegate: Dgsay ("Hello");

3. Multicast delegation
A delegate that typically contains multiple method pointers is called a multicast delegate
In fact, each user-defined delegate type compiled is a class inherited from the multicast delegate, see the Source:

Upload Image:

4. Purpose of the Commission
(1) The method can be passed as a parameter and a return value
(2) Call a delegate to execute N methods (multicast delegate)

5. Disadvantages of Delegation
Disadvantages of not controlling: You can use Click=null to clear all registered events, and you can use Click () to impersonate an event trigger.
Solution, the delegate member is made private, then add Addclickeventhandler, Removeclickeventhandler two public methods

6. What is an event
Control encapsulation of the accessibility of a delegate variable
Syntax: public delegate void Dgsayhi (string name);
Public event Dgsayhi dgsay;//Create event delegate (essentially or delegate object)
Event will automatically generate a private delegate variable and two functions: the Add and remove,c# compilers support the + = and-= Operators with both methods

usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceconsoleapplication1{ Public Delegate voidDgeach (intIndexObjectitem);  Public Delegate voiddgtest (); Internal classProgram { Public Static voidTest1 (dgtest dgtest) {dgtest ();//after compiling: Dgtest.invoke ();Console.WriteLine ("Test1"); }         Public Static voidTest2 () {Console.WriteLine ("Test2"); }         Public Static voidTest3 () {Console.WriteLine ("Test3"); }        /// <summary>        ///delegate when return value/// </summary>        /// <param name= "Strtype" ></param>        /// <returns></returns>         Public StaticDgtest Invoketest (stringstrtype) {            Switch(strtype) { Case "2":                    returnTest2;  Case "3":                    returnTest3; default:                    returnTest3; }        }        /// <summary>        ///using delegates to mimic the jquery each method/// </summary>        /// <param name= "list" ></param>        /// <param name= "func" ></param>         Public Static voidEach (ArrayList list, Dgeach func) { for(inti =0; I < list. Count; i++) {func (I, list[i]); }        }        Private Static voidMain (string[] args) {            #regionDelegate when parameter//dgtest dgtest = new Dgtest (TEST2);//or dgtest dgtest = Test2; //Test1 (dgtest);            #endregion            #regionDelegate when return value//dgtest dgtest = Invoketest ("2"); //dgtest ();            #endregion            #regionComplete each method//ArrayList list = new ArrayList (); //list.            Add ("Andy Lau"); //list.            ADD ("Jacky"); //list.            ADD ("Aaron Kwok"); //list.            Add ("Dawn"); //Each (list, delegate (int index,object item)// {            //Console.WriteLine (index+ "---------" +item.            ToString ()); // });            #endregion            #regionEvent exercise, a design pattern topic, said there were three objects, cat, mouse, man, cat saw the mouse, the mouse frightened away, in the process to wake the people, in the programming process to pay attention to the new object of participationCat C=NewCat (); C.name="Tom"; C.dgruneventhandler+=C_dgruneventhandler;            C.seemouse (C.name); #endregion        }        Private Static voidC_dgruneventhandler (ObjectSender,eventargs e) {Mouse m=NewMouse (); M.name="mouse1"; M.dgruneventhandler+=M_dgruneventhandler;        M.mouserun (m); }        Private Static voidM_dgruneventhandler (Objectsender, EventArgs e) {Person P=NewPerson ();        P.wakeup (sender); }    }         Public classCat { Public EventEventHandler Dgruneventhandler;  Public voidSeemouse (stringname) {Console.WriteLine (name+"See the mouse"); if(Dgruneventhandler! =NULL) {Dgruneventhandler ( This,NewEventArgs ()); }            }             Public  stringName {Get;Set; } }         Public classPerson { Public voidWakeUp (Objectsender) {Console.WriteLine (Sender asMouse). name+"The mouse runs, the man wakes up."); }             Public stringName {Get;Set; } }         Public classMouse { Public EventEventHandler Dgruneventhandler;  Public voidMouserun (Objectsender) {Console.WriteLine (Sender asMouse). name+"Mouse Run"); if(Dgruneventhandler! =NULL) {Dgruneventhandler ( This,NewEventArgs ()); }            }             Public stringName {Get;Set; } }}

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.