In-depth disclosure event (on)

xiaoxiao2021-04-07  391

In-depth disclosure event (on)

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.

To Be Continue

转载请注明原文地址:https://www.9cbs.com/read-132515.html

New Post(0)