C # Learning (i): Delegates and events

Source: Internet
Author: User

Pre-knowledge

Before learning about delegates and events, we need to know that many programs have a common requirement that when a particular program event occurs, other parts of the program can get notifications that the event has already occurred.

The Publisher/subscriber Model can meet this requirement. In simple terms, in this mode, the Publisher defines events that may be of interest to other parts of a series of programs. Other classes can be "registered" so that they can be notified by the Publisher when these events occur. These subscriber classes get notified by providing a way for publishers to "register". When an event occurs, the publisher "triggers an event" and then executes all events submitted by the Subscriber.

Note: A method provided by a subscriber is called a callback method , or a callback function , and the callback function can refer to https://www.zhihu.com/question/1980113 .

After a general understanding of the underlying mechanism, let's look at the delegates and events:

What is a delegate?

Delegates, like classes, are a type of user customization. But a class represents a collection of data and methods, whereas a delegate holds one or more methods, and a series of predefined actions (you can temporarily interpret it as a type-safe C + + function pointer ). You can use delegates by doing the following:

1) Declares a delegate type (similar to a method declaration, but the delegate does not implement the block)

public delegate void Mydel (int x);//format as [modifier] [delegate keyword delegate] [return type] [delegate name] [signature]

2) Declare a delegate variable using the delegate type.

Mydel Delvar;

3) Create an object of the delegate type and assign it to the delegate object. The new delegate object includes a reference to a method that is consistent with the signature and return type of the first step.

You can create a delegate object like this:

Delvar = new Mydel (someclass.method);                 Create a delegate and save a reference to the first method

or use a shortcut syntax, such as this:

Delvar = Someclass.method;

4) The delegate can also be assigned, but the old delegate reference is reclaimed by the GC.

Delvar = new Mydel (SOMECLASS.METHOD1);//Create a new delegate object delvar = OTHERCLASS.METHOD2; After the assignment, the reference to the previous Method1 is overwritten by the METHOD2

5) Add or remove other methods for the delegate object

Add Method Delvar  + = Somemethod1;delvar  

6) Combination of delegates. The two delegate combinations can be generated as a new delegate, and the invocation list of the new delegate connects the invocation list copies of the other two delegates.

Mydel DelA = someclass.method1; Mydel Delb = otherclass.method2; Mydel DELC = DelA + Delb;

7) Call the delegate. Calling a delegate is the same as calling a function method, and the parameter must be consistent with the method in its invocation list. When the delegate is invoked, all methods in its invocation list are executed. (Note: The delegate cannot be empty when invoked)

Delvar (Parameters);

Other Precautions: 1. When a delegate with a return value is called, the return value of the delegate is the return value of the last method in its invocation list. 2. When a delegate with a reference parameter is called, the parameter is changed according to the return value of one or more methods in the invocation list.

What is an event?

In a nutshell, an event is like an encapsulation of a simple delegate dedicated to a particular purpose. Alternatively, the event contains a private delegate (that is, you cannot access the event directly).

In addition, there are fewer actions available in the event than delegates, and for events we can only add, delete, or invoke event handlers. When an event is triggered, it invokes the corresponding delegate to invoke the method in the invocation list in turn.

For the use of events,. The NET Framework provides a standard pattern that defines a standard delegate type of EventHandler.

EventHandler declares as follows:

public delegate void EventHandler (Object Sender,eventargs e)
Sender holds a reference to the triggering event because it is an object, so it can match any type of instance (you can use the as operator to split the box)
EventArgs is the base class for all event information, and you can declare an event information class that inherits from EventArgs to hold some data information that needs to be passed.

Declare the event that corresponds to EventHandler :

public event EventHandler Someevent;

Note: You can declare a custom standard delegate type in the format delegate void Xxxxhandler (Object Sender,eventargs e).

Adding a Remove event handler is similar to a delegate, and here is no longer a repeat.

Said so much, it is best to do hands-on practice, so as to consolidate their knowledge of learning.

A small example of application

LOL is now a lot of people (including me) very much love a very popular 5v5 multiplayer game, this game in the side of the 5 people by duty divided into single, play wild, Auxiliary, single, auxiliary. The main thing here is to illustrate the triggering mechanism of the event by playing wild and a simple interaction on the order. The specific code is as follows:

1 usingSystem;2 usingSystem.Threading;3 4 namespaceEventstudy5 {6 7     8 9      Public classTop//Event Publisher (previous order)Ten     { One          Public stringHero {Get;Set; }//Use of Heroes A          Public intHP {Get;Set; } = -;//Hero Health Value -          Public Delegate voidLowhphandler (Objectsender, Lowhpeventargs e);//declaring a Microsoft standard type of Delegate -          Public EventLowhphandler lowhpevent;//declaring an event of the delegate type the  -          Public classLowhpeventargs:eventargs//Low Life Event information -         { -              Public ReadOnly stringLowhphero; +              Public intRESTHP {Get;Set; } -              PublicLowhpeventargs (stringHeroint_resthp) +             { ALowhphero =hero; atRESTHP =_RESTHP; -             } -         } -  -          Public voidBacktobase ()//Back to town supplies -         { inConsole.WriteLine ("{0} returned to the town.", Hero); -HP = -; toThread.Sleep ( the); +Console.WriteLine ("he sent it back to the road."); -         } the  *          PublicTop (stringHero//constructor Function $         {Panax NotoginsengHero =hero; -         } the  +  A          Public voidFight (intbattlecounts)//Battle battlecounts = number of battles the         { +              for(inti =0; I < battlecounts;i++)//Battle Flow -             { $Console.WriteLine ("our order {0} is in a fierce alignment with the other side ...", Hero); $Thread.Sleep ( -); -HP-= -; -Console.WriteLine ("remaining health after combat: {0}", HP); theThread.Sleep ( +); -                 if(HP <= -)//When the health value is less than or equal to 100Wuyi                 { the                         if(Lowhpevent! =NULL)//If an object is registered -Lowhpevent ( This,NewLowhpeventargs (Hero, HP));//Triggering Events Wu                         Else -Console.WriteLine ("{0} said: "Grass, no one is concerned about the road ah?" ", Hero); About                      Break; $                 } -             } -         } -  A     } +  the     classJungle//subscribers (playing wild) -     { $              Public stringHeroname;//Use the Hero name the              PublicJungle (stringName//constructor Function the             { theHeroname =name; the             } -              Public voidHelp (ObjectSender,top.lowhpeventargs e)//callback function, or event handler . in             { theConsole.WriteLine ("{0} said: The slot, our order {1} only: {2} blood, I have to help him.", Heroname, E.lowhphero, E.RESTHP); the             } About     } the  the  the  +     class Program -     { the         Static voidMain (string[] args)Bayi         { the             //Create a single and a dozen wild theTop Yassuo =NewTop ("Gale Sword Ho-ya-sok");  -Jungle Leesin =NewJungle ("Blind Monk-Li Qing"); -  theYassuo.lowhpevent + = Leesin.help;//Li Qing began to pay attention to the life of Yasuo. theYassuo.fight (4);//The cable starts and pairs the face line when the event is reached, and then executes the corresponding delegate (that is, callback the Help method for the Li Qing that has already been registered) theYassuo.backtobase ();//The amount of subcellular blood is too low to return to the town. Reset HP to theYassuo.lowhpevent-= Leesin.help;//Li Qing no longer pays attention to the return of Asia -Yassuo.fight (4);//the cable continues and on the face line when it reaches a particular situation and triggers the event, but Li Qing has canceled attention, the event is processed as empty, so the direct printing of the words of the request said theConsole.ReadLine ();//Pause the         } the     }94}

The corresponding console output is as follows:

Here is basically the Blind Monk's Help method registered Yasuo Low-volume event lowhpevent, when Yasuo low blood volume triggered the event, and then through the corresponding delegation callback the blind Monk Help method. After the return of the town, the blind Aberdeen canceled the attention of the low-volume cable incident. So after Yasuo again low blood volume, because there is no corresponding event handler (lowhpevent = = null), so Yasuo began to spit Groove no one to the road.

Reference information about:

C # Illustrated Tutorial (fourth edition) Beauty Daniel M.solis

Plain English series of C # delegates and Events : http://www.cnblogs.com/wudiwushen/archive/2010/04/20/1703368.html Bogota 2010

It is known that the callback function is related to: https://www.zhihu.com/question/1980113.

C # Learning (i): Delegates and events

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.