C # How to thoroughly understand "events and delegation"

Source: Internet
Author: User
Tags class manager
Copenhagen

Events and delegation seem to be hard to understand, because their usage is very different from common encodings. For example, we usually write Synchronous Code and call a type of method, the result of method execution is displayed immediately, which is logical. However, in some cases, the Synchronous Code may not meet the requirements. Take the bus for example, if the Traffic Control Center wants each bus to send a signal to itself when arriving at a site so that they can know the traffic conditions at any time, and use the Synchronous Code, the public steam object must certainly call the control center object, in this case, two types are closely coupled. Since other types need to respond to their own behaviors, it seems inevitable to call methods of their types in person. In synchronous code, it is difficult to avoid this close type call relationship. The other difference is that in general, we only pass attributes as parameters to methods, but seldom consider passing one method to another method. We discard the difficult concepts of events and delegation in various C # reference books, and imagine a scenario to understand the use of events and delegation: an IT company, the chairman does not want his employees to play games during work hours, but may not stare at every employee all the time. Therefore, he wants to use a new method to monitor employees: if an employee violates regulations, a device or a specialized invigilator will automatically send a message to him, and the chairman of the board only needs to handle the incident. Therefore, this use case is actually an interaction between the Chairman and employee. The following code shows you how to use the delegate and event mechanism to implement this interaction: first, we need to define a delegate type between the chairman class and the employee class to transfer events between the two. This type is a monitoring device or an invigilator responsible for reporting small reports: public delegate void DelegateClassHandle (); defines a definition of a delegate process similar to a method, but it does not have a method body. To define a delegate, you must add the keyword delegate. Since the definition delegate is actually quite a class, you can define the delegate anywhere in the definition class. In addition, you can add general access modifiers such as public, private, and protected based on the delegate visibility. The Return Value Type of a delegate is void, which does not indicate that the delegate type has a return value. The return value type refers to the target function type of the delegate, that is, the return value of an event processing function entrusted by the delegate is void. Create an Employee class Employee with the following code: public class Employee {public event DelegateClassHandle PlayGame; public void Games () {if (PlayGame! = Null) {PlayGame () ;}} an event PlayGame of the DelegateClassHandle type is defined in the Employee class Employee code. Its definition method is also special. You must first use the keyword event, playGame is an event, and the delegate type of this event must be declared as DelegateClassHandle. This type of delegate object will be responsible for notifying the event. If an employee starts playing a game, it will execute the Games method. Once this method is called, an event PlayGame will be triggered, then the Chairman will receive a message about the event-someone is playing a game. The Chairman class code is as follows. He has a method named Notify to receive messages: public class Admin {public void Notify () {System. console. writeLine ("someone is playing game");} How does the PlayGame event of Employee associate with the Admin's Notify y method? You only need to bind an event. The specific process is as follows: Employee employee = new Employee (); Admin admin = new Admin (); employee. playGame + = new DelegateClassHandle (admin. y); employee. games (); pay attention to the code bound to the event: employee. playGame + = new DelegateClassHandle (admin. using DelegateClassHandle to bind the interaction between the two classes. after the Games method is called, the PlayGame event is triggered, and the event will be delegated to the Notify method of admin for handling, notifying the chairman of the board of directors that an employee plays the game during work hours. However, the chairman of the board is not satisfied with this simple notification. He also wants to know who violates the regulations during work hours. Obviously, the required parameters must be passed to the delegate object, which can be easily implemented. The event parameters can be set to any type of data. In the. NET Framework, the event parameter base class EventArgs is also provided for passing event data. A Custom Event parameter class CustomeEventArgs is derived from the EventArgs class, which carries the employee name and age information: public class CustomeEvetnArgs: EventArgs {string name = ""; int age = 0; public CustomeEvetnArgs () {} public string Name {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 include the required parameter: public delegate void DelegateClassHandle (object sende R, CustomeEvetnArgs e); the Code of the Employee class is modified as follows: public class Employee {private string _ name; public string Name {get {return _ name ;} set {_ name = value ;}} private int _ age; public int Age {get {return _ age;} set {_ age = value ;}} public event DelegateClassHandle PlayGame; public void Games () {if (PlayGame! = Null) {CustomeEvetnArgs e = new CustomeEvetnArgs (); e. name = this. _ name; e. age = this. _ age; PlayGame (this, e) ;}} in the Games method, create a CustomeEventArgs object, and set the required attributes Name and Age. The Chairman's notice method must also be modified accordingly: public class Admin {public void Policy (object sender, CustomeEvetnArgs e) {System. console. writeLine (e. name + "is" + e. age. toString () ;}} the code associated with the two types of objects also needs to be modified accordingly: Employee employee = new Employee (); employee. name = "Mike"; employee. age = 25; Admin admin = new Admin (); employee. playGame + = new DelegateClassHandle (admin. y); employee. games (); the modified Code Execution result is that when Mike calls the Games method to play the game, PlayGa is automatically triggered. Me event, and the event carries the relevant information to Notify admin, the latter's Notify y method will receive the data and output "Mike is 25", telling the chairman is Mike, 25 years old, playing games during work hours. A delegate can be a multi-channel broadcast (Mulitcast), that is, an event can be delegated to multiple objects for receiving and processing. In the preceding example, if another manager has the same preferences as the chairman of the board, the delegate can notify the employee of the PlayGame event. First, define the Manager class: public class Manager {public void Policy (object sender, CustomeEvetnArgs e) {System. console. writeLine (sender. toString () + "-" + e. name) ;}} the Notify y method of Manager is the same as that of Admin, and the corresponding information is also received. The delegate multicast binding method still uses the + = Operator. The method is 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. y); employee. playGame + = new DelegateClassHandle (manager. y); employee. games (); when this method is executed, the reader will see that the Notify y methods of admin and manager will be notified and called for execution. In this way, both the Chairman and manager will know that Mike is playing the game. If the Chairman does not want the manager to receive this notification, how can he unbind PlayGame from the manager event? It is also very simple. run the following statement before the Games method is called: employee. playGame-= new DelegateClassHandle (manager. finally, you must note that the Games method in the Employee class must determine whether the event is null before triggering the event PlayGame. When the Games method of the employee object triggers the event PlayGame, a target function must be provided to handle the event, and the statement determines whether the target function exists. If the game method is called directly without binding the event, an NullReferenceException occurs in the event PlayGame. Can the reader draw any conclusions from the delegate and Event code? There are two types that need to have a call relationship, but no actual call code is written in their respective implementations. They only complete the message transmission process through an event and a third-party delegate type. There is no close coupling between the two types. They seem to communicate loose through a delegate object, realizing the "high aggregation" and "low coupling" ideas that have been promoted in this book.

 

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.