C# Knowledge Review - Getting Started with Events

高洛峰
Release: 2016-11-14 13:28:21
Original
1265 people have browsed it

1. What's Event

 A class or object can notify other classes or objects of related things that have occurred through events. The class that sends (or raises) an event is called a "publisher" and the class that receives (or handles) an event is called a "subscriber" (subscriber).

 In a typical C# Windows Forms or Web application, you can subscribe to events raised by controls such as buttons and list boxes. You can use an integrated development environment (IDE) to browse the events published by a control and select the events that you want to handle. The IDE will automatically add a blank event handler method and the code to subscribe to the event.

2. Summary of event attributes

The issuer determines when the event is triggered; the subscriber determines the response to the event.

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

Events without subscribers will never fire.

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

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

Events are based on the EventHandler delegate and the EventArgs base class.

3. Event subscription and cancellation

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 to have your application perform some useful action when the user clicks the button.

 1. Use IDE to subscribe to events

C# Knowledge Review - Getting Started with Events

Figure 3-1-1 Create a new WinForm project

C# Knowledge Review - Getting Started with Events

Figure 3-1-2 The code automatically created when double-clicking Figure 1

C# Knowledge Review - Getting Started with Events

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

  2. Subscribe to events programmatically

Assuming that it is a new WinForm program, we create events ourselves manually. Enter this.Load += under the InitializeComponent method, and then a prompt will appear. At this time, we press the "Tab key",

C# Knowledge Review - Getting Started with Events

Figure 3-2-1

 You will find that the event handler will also be automatically created , the effect can be said to be the same as the code created by directly double-clicking the blank space in the previous section. 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();
        }
    }
Copy after login

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

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //this.Load += Form1_Load;

            //点击事件(lambda 方式创建)
            this.Click += (s, e) =>
            {
                MessageBox.Show($"{((MouseEventArgs)e).Location}");
            };
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
    }
Copy after login

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

C# Knowledge Review - Getting Started with Events

  3. Use anonymous methods to subscribe to events

public Form1()
        {
            InitializeComponent();

            //this.Load += Form1_Load;

            //点击事件(lambda 方式创建)
            //this.Click += (s, e) =>
            //{
            //    MessageBox.Show($"{((MouseEventArgs)e).Location}");
            //};

            //使用匿名方法创建事件
            this.Click += delegate (object sender, EventArgs e)
            {
                var mouseEventArgs = (MouseEventArgs)e;
                var mouseLocation = mouseEventArgs.Location;

                MessageBox.Show($"X: {mouseLocation.X}, Y: {mouseLocation.Y}");
            };
        }
Copy after login

  【Note】If you use anonymous functions to subscribe to events, the unsubscription process of the event will be more troublesome. To unsubscribe in this case, you must return to the event's subscription code, 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 code behind, it is recommended not to use an anonymous function to subscribe to the event.

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 unsubscribing from an event, the multicast delegate in the publishing object that underlies the event references the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, the subscriber object will not be deleted by garbage collection. Use the subtractive assignment operator (-=) to unsubscribe from an event.

This.Load -= Form1_Load; //Use the subtraction assignment operator (-=) to unsubscribe from the event

【Remarks】After all subscribers unsubscribe from the event, the event instance in the publisher class will be set to null.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!