C # Events

Source: Internet
Author: User

Events, I believe that starting a C # friends will use, in C # is very common, such as clicking a button, uploading a picture, etc., in WinForm or WebForm in the use of events. Today, taking advantage of the few events, I decided to revisit what I had previously skipped-events.

Well remember before, in the use of a method, if there is a handler parameter inside, it is good to fear, in fact, the event or commissioned to do intermediary, in the event two times to the definition went to the Commission, will be entrusted to copy out, remove delegate is the method signature, Write the code you want to implement to assign a value to the event is OK.

  I. What is an event

Events involve two types of roles: the publisher of the event and the subscriber of the event. The object that triggers the event is called the event Publisher, and the object that captures the time and responds to it is called the event Subscriber.

  Ii. relationship of events and commissions

After an event is triggered, the event publisher needs to publish a message informing the event subscriber of event handling, but the event Publisher does not know which event subscribers to notify, which requires an intermediary between the publisher and the Subscriber, which is the delegate. We know that the delegate has a call list, so that only the event Publisher has a delegate that each event subscriber adds its own event handlers to the invocation list of the delegate, and when the event fires, the publisher only needs to invoke the delegate to trigger the subscriber's event handler.

  Iii. How to declare an event

Declaring an event's syntax is very similar to defining a member of a class, and is very simple. In fact, an event is one of the class members, except that the event definition contains a special keyword: event.

There are two ways to declare an event:

1, the use of custom delegate type.

2, using EventHandler predefined delegate type.

The two approaches are basically the same, except that the second is a common form in the. Net framework, so it is recommended to use the second approach as much as possible.

         keyword  delegate type     time name public    event  EventHandler Printcomplete;

EventHandler is a predefined delegate type in the BCL, which is located in the System namespace to handle events that do not contain event data. Events can be implemented by deriving EventArgs if they need to contain event data.

First look at the signature of the EventHandler delegate:

public delegate void EventHandler (Object sender,eventargs e);

1, the return type of the delegate is void;

2, the first parameter-thesender parameter, which is responsible for saving a reference to the object that triggered the event, because the type of the parameter is the object type, so it can save any type of instance;

3, the second parameter--e parameter, it is responsible for saving the event data, here is the default EventArgs class defined in the BCL, it is in the System namespace, he cannot save any data.

  Iv. Subscribing to Events

The event subscriber role needs to subscribe to events published by the event Publisher in order to receive and respond to the event when it is published, and the event is actually a delegate type, so the event-handling method must match the delegate signature. If the event uses a predefined delegate type: EventHandler, then the event-handling method that matches it is as follows:

    public void Someeventhandler (object sender, EventArgs e)    {         //..    }

With the event handling method, you can subscribe to events by using the addition assignment operator (+ =) only.

  V. Triggering events

    Checks if the event is empty    if (printcomplete! = null)    {         //////As the calling method triggers the event, parameter        printcomplete (this,new EventArgs ();    }

An example of a complete event:

namespace consoleapplication1{public    class program    {        static void Main (string[] args)        {            Console.WriteLine ("Do something done, then trigger the event!");            Eventsample es = new Eventsample ();            Es. Showcomplete + = es. MyEventHandler;            Es. Onshowcomplete ();            Console.readkey ();        }    }    public class Eventsample    {
Define an event public events EventHandler Showcomplete;
    
Trigger event public void Onshowcomplete () { //Determines whether an event-handling method is bound, null means no event -handling method if (showcomplete! = null) {
Triggers the event showcomplete (this, new EventArgs ()) Just like the calling method;} } Event handling method public void MyEventHandler (object sender, EventArgs e) { Console.WriteLine ("Who triggered me?") "+ sender. ToString ());}}}

  Vi. use and expansion of the EventArgs class

As mentioned earlier, the second parameter of the default predefined delegate, EventHandler, cannot itself contain event data. but in many. Net-provided methods, you can call out some information with E because this is not the default EventArgs class. Therefore, you cannot pass state information to an event handler when an event is raised, and if you want to pass state information, you need to derive a class from this class to hold the information.

The following is an example of an extended EventArgs class:

    public class Printeventargs:eventargs    {public        string printstate        {            get;            Set;        }        Public PrintEventArgs (string state)        {            printstate = state;        }    }

And when called, just change the EventArgs to PrintEventArgs

    public void Someeventhandler (object sender, PrintEventArgs e)    {        Console.WriteLine ("Print completed!");    }

Note, however, that at this point the binding event compiler will error:

Enentsample.printcomplete + = ShowMessage; This line code compiler error

Why is it? So the second argument to the event delegate is that the EventArgs type differs from the extended PrintEventArgs, so the old method cannot be bound, so a custom delegate is used.

  Vii. Custom Delegates

Now that the EventHandler delegate is not available, only consider declaring the event with a custom delegate. First declare a custom delegate:

public delegate void Printeventdelegate (Object Sender,printeventargs e);

Next, replace the predefined delegate eventdelegate used in the event declaration with our custom delegate:

public event Printeventdelegate Printcomplete;

Because our extended PrintEventArgs class does not have a constructor with no parameters, we need to modify the code of the event firing section, pass in a parameter, and the value of the parameter is the state information to be sent to the event-handling method, which is replaced by a simple string:

if (printcomplete! = null) {Printcomplete (this,new PrintEventArgs ("test Message")); }

  Viii. Event Accessors

An event is a special multicast delegate that, by default, has a private delegate type variable that holds a reference to the event-handling method of the subscription event, and the variable of this delegate type can only be delegated from the class in which the event is declared. Event subscribers subscribe to events by providing a reference to the event-handling method, which is added to the invocation list of the delegate by default time accessors. The event accessor here is similar to a property accessor, except that the time accessor is named Add and remove, not the get and set of the property. In most cases, you do not need to provide a custom event accessor. If not provided, the compiler automatically adds an event accessor. If you need to add a custom event accessor to support some custom behavior, you can use the following syntax:

Public event MyEventHandler Printcomplete {add {//.    } remove {//.. }  }

After declaring the event accessor, the compiler will not provide a private delegate object, and the management of the Subscriber event-handling method reference requires us to implement it ourselves.

    Public event MyEventHandler Printcomplete    {        Add {MyEventHandler + = value;}        Remove {MyEventHandler-= value;}    }

Here is an example of an extended EventArgs with a custom delegate that passes data to a method:

Namespace consoleapplication1{public class program {static void Main (string[] args) {Con Sole.            WriteLine ("Do something done, then trigger the event!");            Eventsample es = new Eventsample (); Es. Showcomplete + = es.            MyEventHandler; Es.            Onshowcomplete ();        Console.readkey ();        }} public class Eventsample {//This event cannot be used so//public event EventHandler Showcomplete;        Custom delegate public delegate void Showeventdelegate (Object Sender,showeventargs e);         Replace the delegate in the event with your own custom delegate public event Showeventdelegate Showcomplete;            public void Onshowcomplete () {///Determines whether an event-handling method is bound, null means there is no event-handling method if (showcomplete! = null)            {//This time to pass the parameter data showcomplete (this, new Showeventargs ("Pass to your data, then!")); }}//Event handling method, note the second parameter public void MyEventHandler (object sender, Showeventargs e) {C Onsole. WriteLine ("who triggered me" + Sender.            ToString ());        Console.WriteLine ("What data to pass over:" + E.showresult);            }}//Custom EventArgs public class Showeventargs:eventargs {public string Showresult {            Get        Set        Public Showeventargs (string result) {Showresult = result; }    }}

The output results are as follows:

  

  Ix. Comprehensive description of events

In the event, a total of 4 main things.

1. Sender: The object that transmits the trigger delegate;
2, EventArgs: Transmission of the details of the incident;
3, EventHandler: Used to accept the Entrustment method;
4, Delegate: Methods of packaging, allowing the method to pass the past;

For example, when a button is clicked, the delegate is executed (the method EventHandler is bound to), and the delegate program is called, the button 1 (object sender) is clicked (EventArgs e).

A lot of times, because. NET comes with these base classes that do not meet the multiple parameters we need to pass, so sometimes we need to customize the various inheritance classes.

For example, if we drag a text box on WinForm and set the Textbox1_mouseclick event, the generated code is as follows:

private void Textbox1_mouseclick (object sender, MouseEventArgs e) {Console.WriteLine (e.clicks);}

We see the original EventArgs turned into MouseEventArgs.

Its code is as follows, and by contrast, it can pass more parameters.

    Abstract://For System.Windows.Forms.Control.MouseUp, System.Windows.Forms.Control.MouseDown//And System.win Dows.    The Forms.Control.MouseMove event provides data. [ComVisible (true)] public class Mouseeventargs:eventargs {//Abstract://Initialize SYSTEM.WINDOWS.FORMS.M        A new instance of the Ouseeventargs class.        Parameter://button://System.Windows.Forms.MouseButtons One of the values indicating that the mouse button was pressed.        Clicks://The number of times the mouse button has been pressed.        X://The x-coordinate of the mouse click (in pixels).        Y://The y-coordinate of the mouse click, in pixels.        Delta://A signed count of the number of brakes that have been rotated by the mouse wheel.        Public MouseEventArgs (mousebuttons button, int clicks, int x, int y, int delta);        Gets which mouse button was pressed.        Public MouseButtons Button {get;}        Gets the number of times the mouse button is pressed and released.        public int Clicks {get;} Gets the signed count of the number of brakes rotated by the mouse wheel multiplied by the Wheel_delta constant.        The brake is a notch in the mouse wheel.        public int Delta {get;} Gets the mouse when a mouse event occurs.Position.        Public point location {get;}        Gets the x-coordinate of the mouse when the mouse event is generated.        public int X {get;}        Gets the y-coordinate of the mouse when the mouse event occurs.    public int Y {get;} }

  In the final analysis, both object sender and EventArgs e are meant to pass parameters. Custom can pass more parameters.

Demo:http://www.cnblogs.com/kissdodog/archive/2013/03/29/2988646.html of the actual use of events

Transferred from: http://www.cnblogs.com/kissdodog/archive/2013/05/14/3076987.html

C # Events

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.