In-depth disclosure event
Small order
In the last article ("In-depth"), we focus on what is entrusted and entrusted. Have a friend asked: When is it to be delegated - to tell the truth, use a certain programming element is a kind of thought, it is a habit. For example, if you ask me "When I use for loop", I can completely answer - I can't use the for loop, and IF will be able to get it fully - we most people use for loops, it is Because we agree with the idea of the for loop and develop the habit of using the for loop. The delegation is also like this - there is no entrusted day, the programmer is working, but after having a commissioned mechanism, everyone is more convenient, the code writes is higher - when you experience it, naturally Use it, after developing a habit, you know when you should use it. OK, we go back to the topic, and the most common area to entrust it is to declare "incident", or: delegate is the basis of the event. As a sister article "in-depth discussion", this article we mainly discuss events (Event).
text
One. What is an event?
The programming language is an abstraction of human language, so programming language elements are often similar to those corresponding to those in the human language. It is this kind of "similar", so many elements look very well, but if you don't understand it, you will be astrayed. "Event" is one of such elements, let us be careful.
Real world incident
Let us look at the "incident" in the real world.
The "event" in the real world refers to "a big thing to have a certain social meaning or impact." Extract the secondary trunk of the sentence, we can draw: incident = something that makes sense or affected. Therefore, we can see that there are two prerequisites for determining whether it is a "event": first it is a "things", then this matter also wants to "meaningful or influence."
Then we analyze the concept of "things". We often say "one thing happens". This "happens" composition is no foundation, location, participation in the character (subject), the object involved - abstract, we can call these elements "things" Parameters.
One thing happened, it may have an impact on certain objects (Client) or there may be no impact. If things happen, and the object has an impact on the object, when we should take out the impact of this impact.
For example: The fire of the building has rang (the fire sounds this incident), the impact of it is to let everyone in the building heard the sound, and people in the building have taken out the impact of their own influence. Come - ordinary staff flew out the building, and firefighters run in the opposite direction and rush to the most dangerous fire. We refer to the "event response mechanism" to respond to the impact of the event is referred to as "Event Response Method". Special attention: Employee escaping and firefighters rushing to the fire, being a response method for the alarm, rather than the impact of the incident.
By the way, there is a small problem: why should we run? Oh, the answer is very simple - because we always care about the alarm will not respond.
OK, thank you very much for reading the above text - the level of junior high school language can determine if a student can become a qualified programmer.
Concept of the event in .NET Framework
Let's take a look at what "events" (event) in C # is, and how to correspond to the concept of events in the real world.
1. MSDN explained to Event keyword: Events area Used on classes and structs to notify Objects of Occurrences That May Affect Their state. Events are used on classes and structures, where they are notified to some objects - the status of these objects It is possible that it is affected by the incident. 2. MSDN's explanation of Event: An Event Is A Way for a class to provide Notifications When Something Of Interest Happens. Event is a way to provide notifications when certain things that are concerned.
3. Explanation of Event members in C # SPEC: an Event Is A Member That Enables An Object Or Class To Provide Notifications. Clients Can Attach Executable Code for Events By Supplying Event Handlers. Event is a member, which makes objects or classes Provide notifications. The client (notified object / class) can be added to the event to respond to events, which are called "event handlers).
4. I own interpretation: Events is a kind of member of class and structs, and it is a way for class and structs who own the events to notify objects who cares these events and provides the event handlers when these events fire.
Event is a member of class and structures. When an event occurs, "Event" is a class / structure notification of this event (or "subscribe") of these events and provides an object of the event processor.
There is no meaning, let's give the corresponding code, lead you to experience what is incident, how the event is declared, how to subscribe to other classes, how to subscribe to the class, how to respond (processing) Event.
We will use the building fire alarm as an example, give the following code:
/ / ============= Water true ============ //// http://blog.9cbs.net/fantasiax///= ======== On the water, lanting silent =========== ============================================================================================= The "agreement" delegate void fireArmDelegate () Delegate void FireArmDelegate () delegate (class) class building {// declared event: Events are delegated to the basis of the publicmreamdelegate fireararrmring; // The building is fired, trigger Fire Alarm Resound Event Public void onfire () {this.fireAlarmRing ();}} // Employee (class) Class Employee {// This is the response of the staff to the fire event, ie employee's Event Handler. Pay attention to the match of the commission. Public void runaway () {console.writeline ("Running awary ...");}} // Firefighter (class) class fireman {// This is the response of firefighters to fire events, namely firefighters Event Handler. Pay attention to the match of the commission. Public void rushintofire () {console.writeline ("Fighting with Fire ...");}} Class Program {static voidmain
(String [] args) {building sigma = new building (); Employee Employee = new EMPLOYEEE (); fireman fireman = new fireman (); // The impact of the event "Subscribe" event starts to care about this incident .FireAlarmRing = new fireAlarmDelegate (Employee.Runaway); sigma.fireAlarmRing = new fireAlarmDelegate (Fireman.Rushintofire); // is made by you! Console.writeline ("please input" ""); string str = console.readline (); if (str.toupper () == "fire") {sigma. Onfire (); }}} The above code mentioned that the event is based on the entrustment, but the commission is not only the basis of statement, but also a "agreement" that the transmission and reception of the parties must work together. OK, let us improve the above example to further play the power of the event. Imagine such a situation: a total of 7 floors in the building, all the fire prevention is not bad, as long as the fire is particularly big, there is no need to let everyone evacuate - which layer is fire, which layer of employees are evacuated. There is also a level of fire: we divide the size of the fire into three levels -
C-class (small fire): A fire machine level, my brothers on the left better like smoking, I don't run when he is smoke.
B (fire): Big, requires the personnel of the floor to evacuate.
A level (big fire): General girlfriend's temper is this level, requiring the whole floor to evacuate.
OK, let's take a look at the code:
/ / ============= Water true ============ //// http://blog.9cbs.net/fantasiax///= ======== On the water, lanting silent =========== ================2; Namespace eventsample {// event parameter class: record fire Floor and Level Class FireEventArgs {Public Int FLOOR; PUBLIC CHAR FireElevel;} // Entrusted is the basis of the event, which is the "agreement" delegate void FireArmDelegate (Object Sender, FireEventArgs E), which is notified by the sender and the recipient. Building (class) class building {// Declaration Event: Events Baset FireArmDelegate FireAlarmRing; // Building Fires E.FLOOR = floor; e.fireevel = level; this.fireAlarmring (this, e);} public string buildingname;} // employee (class) Class Employee {public string WorkingPlace; public int workingfloor; // This is employee The response to the fire event, that is, the employee's Event Handler. Pay attention to the match of the commission. public void RunAway (object sender, FireEventArgs e) {Building firePlace = (Building) sender; if (firePlace.buildingName == this.workingPlace && (e.fireLevel == 'A' || e.floor == this.workingFloor) ) {Console.writeline ("Running awary ...");}}} // Firefighter (class) class fireman {// This is the response of firefighters to fire events, namely firefighters Event Handler. Pay attention to the match of the commission.
Public void Rushintofire (Object Sender, FireEventAntargs E) {Console.WriteLine ("Fighting with Fire ...");}} Class Program {static voidmain
(String [] args) {Building sigma = new Building (); Employee employee = new Employee (); Fireman fireman = new Fireman (); sigma.buildingName = "Sigma"; employee.workingPlace = "Sigma"; employee.workingFloor = 1; // The impact of the event "Subscribe" event starts to care about this incident does not happen to happen to happen to happen .fireAlarmRing = new fireAlarmDelegate (Employee.Runaway); sigma.fireAlarmRing = new fireAlarmDelegate (Fireman.Rushintofire); // You come to let go! Console.Writeline ("please input" fire 'to fire the building ... "); string str = console.readline (); if (str.toupper () ==" fire ") {sigma.onfire (7,' C ');}}}} We carefully analyze the above code:
1. More than one of the first examples, this example is a Class FireEventArgs class. This class is specifically used to pass the "fire" parameters - please go back to see the "In the real world" - We care about the location of the fire and the level of fire, because we have two member variables in this class.
2. The next entrustment has changed, which will become two parameters - Object Sender, FireEventArgs E, everyone may ask: Why do you write two parameters without 3 or 4? Oh ... Traditional habits, this traditional start should be traced back to the VC's Win32 era. At that time, the parameters passing the message are a LPARAM and a WPARAM, carrying a variety of useful information - VB mimics them A change name called Sender, a change name called E, then C # has passed through VB, and there is what you see. As for why the first parameter is an Object type, explains to some "polymorphism" knowledge, here I don't say it, I will be in the "deep-in-depth". The second parameter uses our own class, this class with two useful information, which also mentioned above.
3. In the ONFire method function of the building class, the passage of the parameters is performed - you can understand these parameters (one is this, which is this, the other is E, carrying important information) The recipient, that is, the class sent to care / subscribe to this event. In our example, the objects of the BUILDING class event are Employee and Fireman, respectively, they get notifications when the event occurs, and filter themselves from the event parameters passed to their event parameters. This screening is done by the programmer. In this example, Employee has been filtered on the news, and the Fireman class is not filtered, and when you see the fire, you are a bit worried about my brother on the left.). 4. Note: The building class has a buildingName domain because building is the holder of the event, so when the event is inspired, it is also a sender of the message, so this buildingname domain will also send out with this. . If you understand what is multi-state, then OK, you will understand why you can use building fireplace = (building) Sender; read this buildingname.
5. The Employee class is the most interesting class in this program. It not only provides an impact on the Build class event, but also intelligently screening the event - only when the building alarms you work, and it will be evacuated when you are in your floor. Please carefully analyze the Public Void Runaway (Object Sender, FireEventArgs E) method.
6. Unlike the Employee class, the Fireman class is not filtered on the event - you think, fire extinguishing is the responsibility of the firefighter, no matter where you are fire, they will be grateful!
7. Enter the main program, the code is quite clear -, this is indeed, the code of the basic class library is always complicated (in this case, the basic class library refers to several classes of building, employee, fireman). Under normal circumstances, the developer of the basic class library and the main program is not a person. The source code of the basic class library is generally not open to the main program developers, but is issued in the form of a DLL (Assembly) file, so actual development The entire program looks very clear.
8. sigma.fireAlarmRing = new fireAlarmDelegate (Employee.Runaway); sigma.fireAlarmring = new fireAlarmDelegate (Fireman.Rushintofire); What can you see by these two sentences? Oh, because the incident is based on the delegation, the event is also multicast! If you don't understand what is multicast entrust, please refer to "Deep Delivery".
9. Because of employee
Allf
Work, so the 7-layer C-class fire does not cause its evacuation - only firefighters will respond.
two. The origin of the event is no "event" in the traditional concept of object-oriented concept. Traditional object-oriented concepts only data (DATA, also known as Field, domain, member variable), and method (Method, is also member functions, function). If I have not remembered, then this concept appears in Microsoft's COM technology, but because VB is based on ActiveX (one of COM), the concept of "incident" has passed through VB, for many Programmers are well known and used - I am one of them. .NET Framework is actually a higher level package for COM - to know, before the name .NET Framework, it is called "COM
3
"
Come - naturally retained support for events.
three. The meaning of the incident "Evolution" said: "The product is competitive, reasonable,"
Microsoft said: "I am a boss, there is reasonable!"
No matter whether Microsoft is playing big cards, the presence of merits - the existence of an event has brought a lot of convenience to the development of the procedure. From the design level, it makes the procedure concise and clear, easy to maintain; from the technical level, it is a beautifully unknown Windows message delivery mechanism, which greatly reduces programmers. The entrance to the job.
From a software engineering perspective, an event is a notification mechanism that is a way to maintain synchronization between classes and classes.
Ask: What is synchronization?
Answer: Message synchronization!
four. Email Email - Package Events Passing the message can be excited (Fire, also known as "trigger), and a member event included in a class can be excited in a variety of situations. The most typical: a button Click event, can be stimulated by the user to use the mouse, or by testing another software of this software through the Win32 API function to stimulate it.
Let's briefly discuss this CLICK event:
In fact, if you understand the nature of Win32, you should understand that users can't get directly to a control. On the surface, it is indeed that the user clicks on the button with the mouse. In fact, when the user presses the left mouse button, it is sent by the mouse to the Windows operating system "Left-click [X, Y]" message, and then Windows will take this according to the position of [X, Y]. Message assignment (routing) gives controls that should receive it - this is the message delivery / routing mechanism of Windows.
Similarly, when you move the mouse, it seems that the pointer is moving with your will, and it is actually your mouse to report the current location to the Windows operating system with a few hundred times per second, and then Windows will Painting a beautiful pointer "painting" to you on the screen - haha, we are all cheated!
However, these contents are invisible for C # programmers - all packaged as "events". Therefore, from the mechanism of Windows systems, the event mechanism is a package for Windows message delivery mechanism.
The following code is an simulation of the WinForm program automatically generated by Visual Studio 2005. After reading, you can write a WinForm yourself and analyze the mechanism.
Code:
/ / ============ 水 = ============ //// //// http://blog.9cbs.net/fantasiax // // / / / ======== On the water, the moisturizer is silent ========== // use system; use system.collections.Generic; use system.text; using system.windows. Forms; // Add a reference to System.Windows.Forms and System.Drawing assemblies! Using system.drawing; namespace emulatewinform {// Custom EmulateForm class, derived from the Form class. Class emulateform: form {// Two control private button mytextbox; // Initialize the various controls and form itself and adds controls to the form of the control.
private void InitializeComponent () {myButton = new Button (); myTextBox = new TextBox (); myButton.Location = new System.Drawing.Point (195, 38); myButton.Size = new System.Drawing.Size (75, 23 ); Mybutton.text = "Click Me"; MyButton.Click = new eventHandler (MyButton_Click); // Mounting Event Processing Function MyTextBox.location = New System.drawing.point (12, 12); mytextbox.size = New System.drawing.size (258, 20); controls.add (mybutton); text = "emulateform";} // myButton's Click event occurs, EmulateForm class is given to event response functions (Event Handler) Void MyButton_Click (Object Sender, Eventargs E) {MyTextBox.text = "Hello, Event World!";} // Explore the initialization method in the constructor of the EmulateForm class public emulateform ();}} Class Program {static voidmain
(String [] args) {emulateform myform = new emulateform (); Application.run (myForm);}}} code analyzer:
1. To reference using system.drawing; using system.windows.forms; these two Namespace, first manually add a reference to System.drawing and System.Windows.Forms.
2. The EmulateForm class is customized, note that it is derived from the FORM class. For the sake of clarity, I have simplified the code to almost the simplest ... only two member variables. MyButton is an instance of the Button class; MyTextBox is an instance of the TextBox class. The members of the EmulateForm class private void initializeComponent () is exactly the imitation of the real WinForm program. In its function body, instantiate, initialize the member variable, initialize (such as determining size and location), and add them to the form A Controls array. This function will be executed in the constructor of the emulateform.
3. The most important part of this example is to initialize myButton. Note this sentence: MyButton.Click = New EventHandler (MyButton_Click); MyButton.click is MyButton's Click event, you may be strange: How can you declare an incident this time? Oh, because .NET Framework has been prepared for us, you will use it directly. However, we are in order to explore the bottom, so I have to take care of this incident.
4. Detailed analysis of the Button.Click event: First, the event is based on the delegate, then which delegate is based on the MyButton.click event? By looking MSDN, you can find myButton.Click inherited from the Control class, and the EventHandler delegate based - The following is a statement EventHandler delegate [SerializableAttribute] [ComVisibleAttribute (true)] public delegate void EventHandler (Object sender, EventArgs e) If you don't know how the event is declared, go back to the top of "In-depth". " In this statement, in square brackets is Attribute, you don't have to pay attention to it. The key is to see EventHandler's delegate: This delegate parameter list requires the function it histed (for an event is hidden event handler) should have two parameters - Object type Sender and Eventargs type E. What role does this two parameters? Oh, in fact, it is very fun - I have said, the event mechanism is the package of the message mechanism. You can understand the news into a shell, Sender is "Who is a shell", e is "What is the shelling" Of course, the target of the shell is of course the reception of the message. We carefully review the FireEventArgs class written by the last article: Is there two member variables in this class? One is a FLOOR that represents the fire floor, one is representative fire level FireElevel, with the FireAlarmRing event of the Building class instance, the instance E of the FireEventargs class is transmitted to an instance of the Employee class and the Fireman class, and the two instances open "Cannonball" gives the corresponding processing based on the launched content. Just like the shells in the real war, there are regular bombs, wear a bombs, burner, etc., our "news cannonball" is not only one, believe in a few people with everyone: 1 Eventargs class: This is used in the CLICK event The one. It is a regular bomb. Because the user clicking the button is a very simple event, it is not required to carry more information. 2 MouseEventArgs class: is fired by Mousemove, Mouseup, MouseDown event. Its instance carries a lot of other information, the most commonly used one is a x and one y - I can think about it with leg stomach, it is the current position of the mouse. In the following example we show it. 3 Painteventarg Class: Send it from the Paint event. This shell is not simple, and those very beautiful custom controls are inseparable from it! In its belly, there is a Graphics that represents a "canvas" you can paint on the top of the "canvas" ... OK, first list 3 MSDN has their family portraits, the location is System.Eventargs Derived Classes tree. Microsoft can be described as a good job in .NET Framework, Microsoft, from these EVENT ARGS (event parameters), to a variety of entrustments, and then to the five-flowers, all have made good packages, we only need to take it out, it is . 5. Void MyButton_Click (Object Sender, Eventargs E) is the response function of the EmulateForm class for MyButton.Click events (also known as event processors, EventHandler). Pay attention to its parameter list, is it consistent with the EventHandler: P
6. The main program has nothing to say - anew an instance of an emulateform, and use the Application.Run method to execute the program. 7. By the way, it is a correction: What has been explained above - it is the sender of the message. I have repeatedly found this kind of "incident sender" in some books, this is wrong! You think, the incident can only be triggered, excited, how can it be "send"? Not logical ...
Job 1:
Create a WinForm program, as shown. Contains 1 PANEL, 3 Textbox, 1 Button.
Claim:
1. When the mouse slides in Panel, TextBox1 and TextBox2 displays the current X and Y mouse.
2. When the mouse click on the button, TextBox3 wants to display Hello Events World!
prompt:
1. Pay your heart Mousemove event E
2. Trying to use the Visual Studio 2005 use C # 2.0, and use the Partial keyword to store the FORM1 class code in Form1.cs and Form1.Designer.cs, respectively.
Job 2:
Upgrade the program of "in-depth" in-depth event (on) "嘎子 使用 to the version of the event. (I will give it in the next day).
Over
Legal Notice: This article is protected by intellectual property law. If any unit or individual needs to reprint this article, it is necessary to ensure the integrity of the article (any of the authorized or change will be considered infringement). If you need to reprint, be sure to indicate 9CBS in the article to protect the rights of the website; be sure to indicate that the author is Liu Tie, and send mail to Blade @tom.com, indicating the location and use of article. When reprint, please document this legal statement, thank you!