Deep understanding of events and delegates

Source: Internet
Author: User
Tags class manager
Events and delegates seem to be hard to understand because they are used in a way that is very different from commonly used encodings, such as the usual writing of synchronous code, and it is logical to invoke a type of method that immediately results in the execution of the method. In some cases, however, synchronization code may not satisfy demand, take a bus for example, if the traffic control center wants each bus to arrive at a site to send itself a signal so that they can keep abreast of traffic conditions, using synchronization code, the bus object must call the control center object, This is what we have been unwilling to see: Two types are tightly coupled. Since there are other types of reactions to their actions, it seems inevitable that the method of calling their type in person is unavoidable, and it is difficult to avoid such a tight type invocation relationship in synchronization code. Another difference is that, in general, we simply pass the attribute as a parameter to the method, and rarely consider passing one to another method. We discard the quite unruly concepts of events and delegates in various C # Reference books and envision a scenario to understand the use of events and delegates: There is an IT company, the Chairman of the board does not want his employees to play games at work, but it is impossible to stare at every employee at all times, so He wants to use a new way to monitor the effect of an employee: If an employee violates the rules, a device or special inspector will automatically send a message to him, and the Chairman only needs to deal with it when it happens. So this use case is actually the interaction between the two types--the Chairman class and the employee class--The following code will show the reader how to implement this interaction using the delegate and event mechanisms: first, we need to define a delegate type between the Chairman class and the employee class to pass the event between the two. This type is a surveillance device or an inspector who specializes in small reports: public delegate void Delegateclasshandle (); The process of defining a delegate is similar to the definition of a method, but it has no method body. Define delegates be sure to add keyword delegate. Because the definition delegate is actually quite a class, you can define the delegate anywhere in the definition class. In addition, you can add generic access modifiers, such as public, private, and protected, depending on the visibility of the delegate. The return value type of the delegate is void, which does not mean that the delegate type itself has a return value, which is the type of the delegate's target function, that is, the return value of an event-handler function that it delegates is a void type. Create a new employee-class employee with the following code: public class Employee {    public event Delegateclasshandle PlayGame;      PUBlic void Games ()     {        if (PlayGame!= null)   & nbsp;     {            PlayGame ();        }    }} Employees class employee code defines a Delegateclasshandle type of event playgame, and it is defined in a very special way, and you must first use the keyword event to indicate that PlayGame is an event, You must also declare that the delegate type of the event is Delegateclasshandle, that is, the delegate object of that type will be responsible for notifying the event in the future. If an employee starts playing the game, it executes the Games method, and as soon as the method is invoked it triggers an event playgame, and then the Chairman receives the message that the event is being played. Chairman Class code as follows, he has a method Notify is used to receive messages: public class Admin {    public void Notify ()    {  &nbs p;     System.Console.WriteLine ("Someone is playing game");    } How is the PlayGame event of employee associated with the admin notify method? Only through event binding can be implemented, the specific process such as the following code: Employee employee = new Employee (); Admin admin = new admin (); Employee. PlayGame + = new Delegateclasshandle (admin. Notify); Employee. Games (); Please note the event binding code: employee. PlayGame + = new DelegaTeclasshandle (admin. Notify); The interaction of two classes is bound by Delegateclasshandle when employee. After the Games method call, the PlayGame event is triggered and the event is delegated to the Admin Notify method to notify the Chairman that an employee is playing the game during work hours. But the Chairman was not satisfied with the simple notice, and he wanted to know who was violating the rules at the time of work. Obviously, the delegate object must now pass the necessary parameters, and this requirement can be easily done. The parameters of an event can be set to any type of data, and in the. NET Framework, the event argument base class EventArgs is specifically used to pass event data. Derive a custom event parameter class Customeeventargs from the EventArgs class that will carry employee name and age information: public class Customeevetnargs:eventargs {  & nbsp String name = "";     int age = 0;     public Customeevetnargs ()     {}     public string Name   & nbsp {        get {return this.name;}         set { THIS.name = value; }    }     public int age     {         get {return this.age;}         set {this.age = value;}    } Modify the definition of the delegate type Delegateclasshandle to carry the necessary parameters: public delegatevoid Delegateclasshandle (object sender, Customeevetnargs e); The code for the Employee class is modified as follows: public class Employee {    private string _name;     public string name      {        get {_name}       & nbsp set {_name = value;}    }     private int _age;     public int Age     {        get {return _age;} &NB sp;       set {_age = value;}    }     public Event Delegat Eclasshandle PlayGame;     public void Games ()     {        if (PlayGame!=) NULL)         {             Customeevetnargs e = new Customeevetnargs ();           &nbsP E.name = This._name;             e.age = this._age;             PlayGame (this, e);        }    }} in the Games method, first create a new Customeeventargs object, The necessary property name and age are then set. The Chairman's notification method must also be modified accordingly: public class Admin {    public void Notify (object sender, Customeevetnargs e)  &n bsp;  {        System.Console.WriteLine (e.name+ "is" +e.age.tostring ());    } The code that associates two types of objects also needs to be modified: Employee employee = new Employee (); Employee. Name = "Mike"; Employee. Age = 25; Admin admin = new admin (); Employee. PlayGame + = new Delegateclasshandle (admin. Notify); Employee. Games (); The result of the modified code is that when Mike calls the Games method to play the game, the PlayGame event is automatically triggered and the event carries relevant information to notify admin that the Notify method of the latter will receive the data and output "Mike is 25" and tell the chairman that Mike, 25 years old, is working time to play games. Delegates can be multicast (mulitcast), where an event can be delegated to multiple objects to receive and process. In the above use case, if another manager has the same hobby as the chairman of the board, it can also allow the delegate to put the employee's PLAThe Ygame incident informed him. First define the manager class: public class Manager {    public void Notify (object sender, Customeevetnargs e)   &nbsp ; {        System.Console.WriteLine (sender.) ToString () + "-" + e.name);    } The Manager type Notify method is consistent with admin, and he is also receiving the appropriate information. The delegate's multicast binding method is still using the + = operator, as shown in the following code: Employee employee = new Employee (); Employee. Name = "Mike"; Employee. Age = 25; Admin admin = new admin (); Manager Manager = new manager (); Employee. PlayGame + = new Delegateclasshandle (admin. Notify); Employee. PlayGame + = new Delegateclasshandle (manager. Notify); Employee. Games (); By executing this method, the reader will see that the admin and manager notify methods will be notified by the event and invoked to execute. In this way, the chairman and the manager will know that Mike is playing the game. If the chairman does not want the manager to receive this notice, how do I remove playgame from the manager's event bindings? It's also very simple in employee. The following statements can be executed before the Games method is invoked: employee. PlayGame-= new Delegateclasshandle (manager. Notify); Finally, the reader should be reminded that the Games method in the employee class needs to determine whether the event is null before triggering the event playgame. When the games method of an Employee object triggers an event playgame, there must be an objective function to handle the event, which is to determine whether the objective function exists. If you remove this judgment and call games directly without any binding on the eventmethod, the program pops a NullReferenceException exception at the event PlayGame.

Can readers draw any conclusions from the Code of Delegates and events? The two types that need to have call relationships do not write the actual calling code in their respective implementations, they simply complete the message delivery process through an event and a third party delegate type. There is no tight coupling between the two types that seemingly loosely communicates through a delegate object, realizing the "high aggregation" and "low coupling" views that the book has been promoting.

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.