Understanding C # events

Source: Internet
Author: User

Understanding C # events
The previous article introduced the concept of delegation. The program will use this operation by entrusting an instance to save one or more operations at a specific time. If you have developed a GUI program, you may be familiar with the above description. In a GUI program, clicking a button triggers a click event and then executes a series of operations, which are stored in a delegated instance. Next let's take a look at the event. Back to the example of Apple and Foxconn in the previous article using the delegated questions, Apple delegated all iphone assembly, packaging, and transportation work to Foxconn. According to the above description, we modified the code and added an order attribute to the Apple class. As long as Apple receives a new order, it will send a notification to Foxconn, foxconn then executes a series of operations (assembly, packaging and transportation ). In the main program, Apple entrusted Foxconn with iphone assembly, packaging, and transportation, and each time Apple received an order, then, Foxconn will perform a series of operations by entrusting the instance "VerdorToAssembleIphone. Class Apple {// declare the delegate Type public delegate void AssembleIphoneHandler (int num); public AssembleIphoneHandler VerdorToAssembleIphone; public void DesignIphone () {Console. writeLine ("Design Iphone By Apple");} private int orderNum; public int OrderNum {get {return this. orderNum;} set {this. orderNum = value; if (VerdorToAssembleIphone! = Null) {VerdorToAssembleIphone (this. orderNum) ;}}} class Foxconn {// the same method as the delegate type signature public void AssembleIphone (int num) {Console. writeLine ("Assemble {0} Iphone By Foxconn", num);} public void PackIphone (int num) {Console. writeLine ("Pack {0} Ipnone By Foxconn", num);} public void ShipIphone (int num) {Console. writeLine ("Ship {0} Iphone By Foxconn", num) ;}} class Program {static void Main (stri Ng [] args) {Apple apple = new Apple (); Foxconn foxconn = new Foxconn (); apple. verdorToAssembleIphone = new Apple. assembleIphoneHandler (foxconn. assembleIphone); apple. verdorToAssembleIphone + = new Apple. assembleIphoneHandler (foxconn. packIphone); apple. verdorToAssembleIphone + = new Apple. assembleIphoneHandler (foxconn. shipIphone); apple. ordernum= 100; Console. read () ;}let's take a look at the problem in this example: If "=" instead of "+ =" is used incorrectly, the delegate chain disconnects class Program {static void Main (string [] args) {Apple apple = new Apple (); Foxconn foxconn = new Foxconn (); // create a delegated instance apple. assembleIphone = new Apple. assembleIphoneHandler (foxconn. assembleIphone); apple. assembleIphone + = new Apple. assembleIphoneHandler (foxconn. packIphone); apple. assembleIphone = new Apple. assembleIphoneHandler (foxconn. shipIphone); apple. designIphone (); // Call the delegated instance apple. verdorToAssembleIphone (99); Console. read () ;}} events occur. In order to solve the above two problems, the concept of events has emerged. All we need to do is add the event keyword when declaring the delegated instance. Public event AssembleIphoneHandler VerdorToAssembleIphone; at this time, the above two problematic codes will report errors during compilation. The problem above is solved, but what is the role of the event keyword and what is the relationship between the event and the delegate? How does "VerdorToAssembleIphone" understand it? In fact, the following statement is difficult to understand. The first response is what is the relationship between the delegate and the event, and what is the relationship between the event keyword and the delegate type "AssembleIphoneHandler. Public event AssembleIphoneHandler VerdorToAssembleIphone; in fact, an event can be understood as a delegate attribute, which restricts access to the delegated instance by encapsulating the delegated instance. Next we will use IL to check this program and get it. Next we will analyze what the event is based on the results of IL. Before we start, I believe that everyone will be familiar with the concept of property, so let's start from the familiar attributes. C # The concept of attributes first let's look at what we are familiar with. "OrderNum" is the property of the order quantity defined by us. It has a set of get/set methods. Through the get/set Method of this attribute, we can access the "orderNum" field (field ). View the "OrderNum" attribute through IL, and we can see the get/set method corresponding to this attribute. Public int32 get_OrderNum () {} public void set_OrderNum (int32 'value') {} event next let's look at the "VerdorToAssembleIphone" event. We understand the event in the way of attributes. From the perspective of IL, we can see that the event contains a pair of addon/removeon methods to operate on our delegated instance (think about the get/set Method of the attribute ). At the same time, we can see that the compiler generates a private field (as shown below) for us. here we can see that the event "VerdorToAssembleIphone" is essentially a delegate type variable. Because this variable is private, it explains why we cannot directly access this variable outside the class that defines the event.. Field private class _ upload?delegate.apple/AssembleIphoneHandler VerdorToAssembleIphone event Code Conversion Based on the above analysis, we can see that the compiler helps us to convert the following code. In this way, the access to the delegated instance is limited by the event keyword. C # code of the original declaration event: public event AssembleIphoneHandler VerdorToAssembleIphone; Code converted by the compiler: private AssembleIphoneHandler VerdorToAssembleIphone; public void add_VerdorToAssembleIphone (AssembleIphoneHandler 'value ') {} public void remove_VerdorToAssembleIphone (AssembleIphoneHandler 'value') {} through the above analysis, we can see that the event encapsulates the delegate type instance, so that: within the class that defines the event, whether you declare it as public or protected, it is always private. That is to say, you cannot call the event outside the class that defines the event, add" + = "And remove"-= "the access qualifier of the delegated instance is the same as that used when declaring the event. That is to say, if the event is declared as private or this protect, in this case, you cannot perform "+ =" and "-=" operations on events outside the class that defines events. In fact, the above example is just a simple demonstration. In many cases, the event uses two parameters: Event source and event parameter. Therefore, in event programming, you can refer to the following specifications: Use EventNameEventHandler to name the delegate variable: EventName is the event name. delegate accepts two parameters, and the parameter names are named sender and e: the first parameter type is object, the second parameter is event parameter type, named EventNameEventArgs, and must inherit from System. if the EventArgs class does not need to transmit any data in the event, two parameters need to be declared: the first parameter is the default object sender, and the second parameter can use the System default System. the EventArgs class summarizes the concept and principle of the event, explains how to encapsulate the delegate instance through the event, and solves the two problems encountered in the delegate example. We also learned how to use events: declare events by using the event keyword, <event modifier> event <delegate type> <event name>, and call events because they are essentially Delegate types, the call event is the same as the call delegate, but the event call can only happen within the class of the defined event

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.