C # Knowledge review-Getting started with events

Source: Internet
Author: User
I. What ' s event

A class or object can notify other classes or objects about what is happening through events. The class that sends (or raises) an event is called the publisher, and the class that receives (or processes) The event is called a Subscriber.

In a typical C # Windows form or WEB application, you can subscribe to events raised by controls such as buttons and list boxes. You can use the Integrated development environment (IDE) to explore the events published by the control and select the events you want to handle. The IDE automatically adds a blank event handler method and the code to subscribe to the event.

Second, the attribute summary of the event

The issuer determines when the event is raised, and the Subscriber determines the response to the event.

An event can have multiple subscribers. Subscribers can handle multiple events from multiple publishers.

Events that do not have subscribers will never be raised.

Events are typically used to represent user actions, such as clicking a button or a menu option in a graphical user interface.

When an event has multiple subscribers, the event handler is invoked synchronously by default when the event is raised.

Events are based on EventHandler delegates and EventArgs base classes.

Iii. subscription and cancellation of events

If you want to write custom code that is called when an event is raised, you can subscribe to events published by other classes. For example, you can subscribe to a button's click event so that the application performs some useful action when the user clicks the button.

1. Subscribing to events with the IDE

Figure 3-1-1 Create a new WinForm project

Figure 3-1-2 the code created automatically by double-clicking on Figure 1

Figure 3-1-3 In addition to Figure 2, the InitializeComponent method also automatically adds this line of code

2. Subscribing to Events programmatically

Assuming that it is now a new WinForm program, we create the event ourselves by hand. Enter this under the InitializeComponent method. Load + =, then a prompt appears, then we press the TAB key,

Figure 3-2-1

You will find that the event handler is also automatically created, and the code created in the direct double-click space of the previous section can be said to be consistent and the code is as follows:

public partial class Form1:form    {public        Form1 ()        {            InitializeComponent ();            This. Load + = Form1_Load;        }        private void Form1_Load (object sender, EventArgs e)        {            throw new notimplementedexception ();        }    }

This time, we directly use the lambda method to complete the registration of the event: click on the space to display the mouse click on the coordinates.

public partial class Form1:form    {public        Form1 ()        {            InitializeComponent ();            This. Load + = Form1_Load;            Click the event (lambda mode created) this            . Click + = (s, e) = =            {                MessageBox.Show ($ "{(MouseEventArgs) e). Location} ");}            ;        private void Form1_Load (object sender, EventArgs e)        {            throw new notimplementedexception ();        }    }

The "Remarks" content involves the syntax of $: (C # 6), which is supported by vs2015. $ "{msg}" is equivalent to a string. Format ("{0}", msg), MSG refers to a variable.

3. Subscribing to an event with an anonymous method

Public Form1 ()        {            InitializeComponent ();            This. Load + = Form1_Load;            Click event (lambda mode creation)            //this. Click + = (s, e) = =            //{            //    MessageBox.Show ($ "{((MouseEventArgs) e). Location} ");            //};            Use the anonymous method to create the event this            . Click + = Delegate (object sender, EventArgs e)            {                var mouseeventargs = (MouseEventArgs) e;                var mouselocation = mouseeventargs.location;                MessageBox.Show ($ "X: {mouselocation.x}, Y: {MOUSELOCATION.Y}");}            ;        }

NOTE: If you subscribe to an event by using an anonymous function, the unsubscribe process for the event will be cumbersome. In this case, to unsubscribe, you must return to the subscription code for the event, store the anonymous method in a delegate variable, and then add the delegate to the event. In general, if you must unsubscribe from an event in later code, we recommend that you do not subscribe to this event with an anonymous function.

4. Unsubscribe

To prevent the event handler from being called when an event is raised, unsubscribe from the event. To prevent resource leaks, unsubscribe from events before releasing the Subscriber object. Before canceling a subscription event, the multicast delegate that is the basis of the event in the publication object references the delegate that encapsulates the subscriber's event handler. The garbage collection feature does not delete the Subscriber object as long as the publication object holds the reference. Cancels the subscription event using the subtraction assignment operator (-=).

This.  Load-= Form1_Load; To unsubscribe from an event by using the subtraction assignment operator (-=)

Note After all Subscribers unsubscribe from the event, the event instance in the Publisher class is set to NULL.

  • 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.