[. NET] C # knowledge Review,

Source: Internet
Author: User

[. NET] C # knowledge Review,
C # knowledge Review-Introduction to events

[Blogger] Anti-bone Aberdeen [original] http://www.cnblogs.com/liqingwen/p/6057301.html

Collation

I used C # knowledge Review-delegate and C # knowledge Review-delegate (continued) to introduce the basic knowledge of delegation. Here we will look at the event.

 

Directory
  • What's event
  • Event property Summary
  • Event subscription and Cancellation

 

1. What's event

Classes or objects can notify other classes or objects of related events through events. The class for sending (or triggering) events is called "publisher", and the class for receiving (or processing) events is called "subscription" (subscriber ).

In typical C # Windows forms or Web applications, you can subscribe to events triggered by buttons, list boxes, and other controls. You can use the integrated development environment (IDE) to browse events published by controls and select the events you want to process. IDE will automatically add blank event handler methods and code to subscribe to this event.

 

Ii. Event attribute Summary
  • The publisher determines when an event is triggered, and the consumer determines the response to the event.

  • An event can have multiple subscribers. A subscriber can process multiple events from multiple publishers.

  • Events without subscribers will never be triggered.

  • Events are usually used to indicate user operations, such as clicking a button or menu options in the graphic user interface.

  • When an event has multiple subscribers, the event processing program is synchronously called when the event is triggered.

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

 

Iii. Event subscription and Cancellation

If you want to write custom code called when an event is triggered, you can subscribe to events published by other classes. For example, you can subscribe to the click Event of a button so that the application can perform some useful operations when you click the button.

1. Use IDE to subscribe to events

Figure 3-1-1 create a WinForm Project

Figure 3-1-2 The code automatically created when you double-click

Figure 3-1-3 in addition to figure 2, this line of code is automatically added in the InitializeComponent Method

 

2. Subscription events programmatically

Assume that it is a new WinForm program, and we create events manually. Enter this. Load + = in the InitializeComponent method, and a prompt will appear. Press "Tab key ",

 

Figure 3-2-1

 

The event handler is automatically created. The effect is the same as that of the Code created by double-clicking the blank space in the previous section. The Code is as follows:

 1     public partial class Form1 : Form 2     { 3         public Form1() 4         { 5             InitializeComponent(); 6  7             this.Load += Form1_Load; 8         } 9 10         private void Form1_Load(object sender, EventArgs e)11         {12             throw new NotImplementedException();13         }14     }

 

This time, we directly use lambda to complete event registration: The coordinates when the mouse is clicked are displayed in a blank space.

1 public partial class Form1: Form 2 {3 public Form1 () 4 {5 InitializeComponent (); 6 7 // this. load + = Form1_Load; 8 9 // click the event (created in lambda mode) 10 this. click + = (s, e) => 11 {12 MessageBox. show ($ "{(MouseEventArgs) e ). location} "); 13 }; 14} 15 16 private void Form1_Load (object sender, EventArgs e) 17 {18 throw new NotImplementedException (); 19} 20}

[Remarks] content involved$: (C #6) syntax, supported only after vs2015. $ "{Msg}" is equivalent to string. Format ("{0}", msg). msg indicates a variable.

Figure 3-2-2

 

3. Use the anonymous method to subscribe to events

1 public Form1 () 2 {3 InitializeComponent (); 4 5 // this. load + = Form1_Load; 6 7 // Click Event (created in lambda mode) 8 // this. click + = (s, e) => 9 // {10 // MessageBox. show ($ "{(MouseEventArgs) e ). location} "); 11 //}; 12 13 // use the anonymous method to create the event 14 this. click + = delegate (object sender, EventArgs e) 15 {16 var mouseEventArgs = (MouseEventArgs) e; 17 var mouseLocation = mouseEventArgs. location; 18 19 MessageBox. show ($ "X: {mouseLocation. x}, Y: {mouseLocation. y} "); 20}; 21}

[Note] If you use an anonymous function to subscribe to an event, the cancellation process of the event will be troublesome. In this case, to cancel the subscription, you must return the subscription code of the event, store the anonymous method in the delegate variable, and then add the delegate to the event. Generally, if you have to unsubscribe to an event in the code that follows, we recommend that you do not subscribe to this event using an anonymous function.

 

4. cancel subscription

To prevent calling the event handler when an event is triggered, cancel the subscription. To prevent resource leaks, you should cancel the subscription before releasing the subscribers. Before canceling an event subscription, the multicast delegate that serves as the basis of the event in the publish object references the delegate that encapsulates the event handler of the subscription. As long as the published object remains referenced, the garbage collection function will not delete the consumer object. Use the subtraction assignment operator (-=) Cancels the subscription.

This. Load-= Form1_Load; // use the subtraction assignment operator (-=) Cancel subscription event

[Note] After all subscribers cancel the subscription, the event instances in the issuer class will be setNull.

 

Portal

C # knowledge Review-serialization

C # knowledge Review-Expression Tree Expression Trees

C # knowledge Review-feature Attribute and AssemblyInfo. cs-understanding common feature attributes

C # knowledge Review-delegated delegate and C # knowledge Review-delegated delegate (continued)

 

 

[Reference] Microsoft official documentation

 

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.