Delegate and event (2), delegate event

Source: Internet
Author: User

Delegate and event (2), delegate event

Event Origin

As we mentioned above, the Commission is not secure, so we need to privatize the Commission itself, but we need to expose several methods for external use. Among them, the most important thing is to hook up the delegate method and call the delegate to indirectly call the method represented by the delegate. The event keyword is a syntactic sugar provided to us by c. He didn't have anything new, but reduced some code. Therefore, an event is a Special Delegate with the following features:

1. Cooperate with a (base) delegate type. After an event with the delegate type of the base is declared, the user can hook up the event externally, the method type must be the same as that of the base delegate.

2. events can be considered as the delegate method chain. When the event keyword is used, this method chain is private. When the delegate type name is used as the keyword, this method chain is public

3 events are private, but the compiler automatically creates two hidden methods for us and loads + = and-= so that we can not write any additional code, use + = and-= to control the method to be executed when an event is triggered.

Public class Program {public static void Main () {// creates a new subscriber var c = new Car ("Mycar", 0,100); // do you still remember to delegate, if methodList is a CarEngineHandler type, you can write it like this // now methodList is an event type, so the write will report an error // the event can only appear on the left side of + = or-=, it cannot appear on the left of the equal sign. Therefore, users cannot assign values to it at will, ensuring the security of c. methodList = OnCarEvent1; // This is correct c. methodList + = OnCarEvent1; // an event cannot be called externally. // c. methodList. invoke ()} public static void OnCarEvent1 (string msg) {Console. writeLine ("* * *** Message from car *** "); Console. writeLine ("=>" + msg); Console. writeLine ("****************************");} public static void OnCarEvent2 (string msg) {Console. writeLine ("=>" + msg. toUpper () ;}} public class Car {public string name {get; set;} public int currentSpeed {get; set;} public int MaxSpeed {get; set ;} private bool isDead {get; set;} public delegate void CarEngineHandl Er (string message); public event CarEngineHandler methodList; public Car (string name, int currentSpeed, int MaxSpeed) {this. name = name; this. currentSpeed = currentSpeed; this. maxSpeed = MaxSpeed; this. isDead = false;} public void Accel (int delta) {// method if (isDead) {if (methodList! = Null) // There is no difference between the internal call event and the call delegate methodList ("Sorry, car is broken");} else {currentSpeed + = delta; if (currentSpeed> = MaxSpeed) isDead = true; else Console. writeLine ("Current speed:" + currentSpeed );}}}

 

Event code specification

Microsoft has set code specifications for events, which are the same as those for delegates. These specifications mainly include:

1. The delegate name must end with Handler

2. The delegate must have only two parameters. The first is the object-type sender, and the second is a custom class type that integrates the EventArgs type. The name can be customized.

Then we use the code specification to re-write the above example:

Public class Program {public static void Main () {// creates a new subscriber var c = new Car ("Mycar", 0,100); c. methodList + = OnCarEvent1; for (int I = 0; I <10; I ++) {c. accel (20);} Console. readKey ();} public static void OnCarEvent1 (object sender, CarEventArgs e) {// now we know who triggered the event Console. writeLine ("***** message from car:" + sender. toString () + "*****"); Console. writeLine ("=>" + e. message); Console. wri TeLine ("****************************");}} public class Car {public string name {get; set;} public int currentSpeed {get; set;} public int MaxSpeed {get; set;} private bool isDead {get; set ;} // standardized delegate definition // sender: Inform the subscriber who triggered the event when an event occurs. // e: information transmitted when an event occurs (a class can be customized to inherit the EventArgs class, so any type of information can be passed) public delegate void CarEngineHandler (object sender, CarEventArgs e ); public event CarEngineHandler metho DList; public Car (string name, int currentSpeed, int MaxSpeed) {this. name = name; this. currentSpeed = currentSpeed; this. maxSpeed = MaxSpeed; this. isDead = false;} public void Accel (int delta) {// method if (isDead) {if (methodList! = Null) // There is no difference between the internal call event and the call delegate methodList (name, new CarEventArgs {message = "Sorry, this car is dead. "}) ;}else {currentSpeed + = delta; if (currentSpeed> = MaxSpeed) isDead = true; else Console. writeLine ("Current speed:" + currentSpeed) ;}}// format of information sent when a custom event occurs: public class CarEventArgs: EventArgs {public string message {get; set ;}}

 

Sender and EventArgs

I believe that when using. net to drag a control, if you drag a button and double-click it, you will find that the code is several more lines (irrelevant ):

this.button1.Click += new System.EventHandler(this.button1_Click);
private void button1_Click(object sender, EventArgs e){}

But maybe not everyone knows what the two parameters do. I write code in this method, and then click that button, the compiler will execute the code here. In fact, this is an example of an event that complies with Microsoft naming conventions.

1. during initialization, The button#click method is bound to the Click attribute of this object (note that the attribute type is an event and its base delegate is of the EventHandler type. If this event is called, the code of the button#click method is executed.

EventHandler is the most common delegate in the C # control and has no return type:

Public delegate void EventHandler (Object sender, EventArgs e)

We noticed that this delegate is exactly the same as the button#click method signature, that is, we can add the button#click Method to the delegate method chain. Here, the method chain is the event type variable Click.

2. When you click the button, the system finally captures your click action after a series of message polling. After a series of processingControl. OnClick (System. EventArgs e)Method

3. Call the event in this method

Protected virtual void OnClick (EventArgs e) {// retrieve the delegate EventHandler handler = (EventHandler) base named EventClick from the Events delegate set. events [EventClick]; // if not empty, execute the delegate method, that is, button#click if (handler! = Null) {// this is button1 handler (this, e );}}

 

The entire process is:

1. Your click action is captured by windows. windows sends this action (this. button1.Click) to the program as a system message (underlying message polling mechanism)

2. The program continuously extracts messages from its own message queue and finds corresponding processing methods in the message loop.

3. for this message, its sender (event source) Is this button, and all the messages sent are in e. In some events, e is of little use, for example, in the Mouse event of MouseEventArgs, we can see that e includes the coordinates of the mouse for your program to use.

4. Because this. button1.Click is attached with the method button#click, execute the following code:



Therefore, when you click a button, the compiler has already done a lot of things for us, such as delegate creation, event mounting, and execution, these are encapsulated to the extent that you do not need to know or write the code that is successfully executed. Then the topic of delegation and event is almost over (at the level of c #1.0 ). In a later version of c #, delegation and events are encapsulated more easily and easily. The emergence of delegation actions and func Based on generics is even more (basically) it completely replaces the native delegate. Of course, these wonderful contents will be described in the introduction of c #2 and 3.

 

References

Http://www.cnblogs.com/leslies2/archive/2012/03/22/2389318.html

Http://www.tracefact.net/csharp-programming/delegates-and-events-in-csharp.aspx

Http://www.cnblogs.com/zhili/archive/2012/10/29/ButtonClickEvent.html

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.