In-depth introduction (Part 1)

Source: Internet
Author: User

Small order

In the previous article ("delegation in simple terms"), we focused on delegation and its usage. Some friends asked: When to use delegation-To tell the truth, using a certain programming element is an idea and a habit. For example, if you ask me "when to use a for loop", I can answer the question-for loop is not needed at all, if and goto can be used to solve this problem. Most of us use the for loop because we recognize the idea of the For Loop and develop the habit of using the for loop. The same is true for delegation-programmers are working the same day without delegation, but with the delegation mechanism, it is easier for everyone to do and the quality of the Code to be written is higher-when you experience it conveniently, use it naturally, and develop a habit, you will know when to use it. Okay, let's get back to the subject. One of the most common areas of delegation is to declare "Events", or: Delegation is the basis of events. As a companion to "let alone let us talk about events ).

Body

1. What is an event?

Programming Language is an abstraction of human language. Therefore, the elements of programming language are often similar to the words in human language. This kind of "closeness" makes many elements seem easy to understand, but if they are not carefully understood, they will go astray. "Events" are one of these elements and let us be careful.

Events in the real world

Let's take a look at "events" in the real world ".

In the real world, "events" refer to "major events with certain social significance or impact ". Extract the second-level trunk of a sentence and we can conclude that the event is a meaningful or influential thing. Therefore, we can see that there are two prerequisites for determining whether an "Event" is an "Event": first, it is a "Event", and then it must be "meaningful or influential ".

Next, we will further analyze the concept of "things. We often say that "one thing has happened". The elements of this "occurrence" are nothing more than time, place, participants (subjects), and objects involved-Abstract A Little, we can call these elements a "thing" parameter.

An event may have an impact on some objects or clients. If something happens and has an impact on the object, then we should come up with a way to influence it.

For example, if a building fire is triggered (a fire is triggered), the impact of the fire is that all the people in the building have heard the alarm, people in the building have come up with their own methods to respond to this impact-ordinary staff rushed out of the building, while firefighters ran in the opposite direction and rushed to the most dangerous fire. We call this routine an "Event Response Mechanism". The action taken to respond to the impact of an event is referred to as "Event Response Method ". Note: The escape of employees and the rush of firefighters to the fire are responses to the incident, rather than the impact of the incident.

By the way, there is another small problem: Why are we running when the fire strikes? The answer is simple-because we are always concerned about whether the alarm will trigger this event.

OK, thank you very much for reading the above text-the level of junior high school Chinese teachers can determine whether a student can become a qualified programmer in the future.

Concepts of events in. NET Framework

Next let's take a look at what "Event" in C # Corresponds to the concept of "Event" in the real world.

1. msdn's explanation of the event Keyword:
Events are used on classes and structs to policy objects of occurrences that may affect their state.
Events are used in classes and struct. They are used to notify certain objects that their statuses may be affected by events.

2. msdn's explanation of event:
An event is a way for a class to provide configurations when something of interest happens.
Events are a way to provide notifications when some of the things of interest occur.

3. C # SPEC:
An event is a member that enables an object or class to provide configurations. Clients can attach executable code for events by supplying event handlers.
An event is a type of member that enables objects or classes to provide notifications. The client (the notified object/class) can attach some executable code to the event to respond to the event. These executable codes are called event handlers ).

4. My own explanation:
Events is a kind of member of class and structs, and it is a way for class and structs who own the events to your y objects who cares these events and provides the Event Handlers when these events fire.

An event is a member of a class and struct. When an event occurs, the "event" is a type of notification concern (or "subscription") that owns the event class/struct ") these events and provide a way for the event processor objects.

 

 

I am still giving the corresponding code, we will show you how events are declared, how events are subscribed to by other categories, and how the subscribed events respond to (handle) events.

 

Let's take building fire as an example and provide the following code:

// ===================== The true meaning of Water ====================
//
// Http://blog.csdn.net/FantasiaX
//
// ============ Good deeds, good deeds, silent deeds ==============
Using system;
Using system. Collections. Generic;
Using system. text;

Namespace eventsample
{
// Delegation is the basis of the event and the "Agreement" that both parties of the notification and the recipient comply"
Delegate void firealarmdelegate ();

// Building (class)
Class Building
{
// Declare an event: the event is based on delegation.
Public event firealarmdelegate firealarmring;

// Fire in the building, resulting in fire alarms
Public void onfire ()
{
This. firealarmring ();
}
}

// Employee (class)
Class employee
{
// This is the employee's response to the fire event, that is, the employee's event handler. Pay attention to the matching with the delegate.
Public void runaway ()
{
Console. writeline ("Running awary ...");
}
}

// Fireman (class)
Class fireman
{
// This is the fireman's response to the fire event, that is, the fireman's event handler. Pay attention to the matching with the delegate.
Public void rushintofire ()
{
Console. writeline ("fighting with fire ...");
}
}

Class Program
{
Static void main (string [] ARGs)
{
Building Sigma = new building ();
Employee Employee = new employee ();
Fireman fireman = new fireman ();

// The influencer of the event subscribes to the event and starts to care that the event has not occurred.
Sigma. firealarmring + = new firealarmdelegate (employee. Runaway );
Sigma. firealarmring + = new firealarmdelegate (fireman. rushintofire );

// You will set fire!
Console. writeline ("Please input 'fire' to fire the building ...");
String STR = console. Readline ();
If (Str. toupper () = "fire ")
{
Sigma. onfire ();
}
}
}
}
As mentioned in the code above, the event is based on delegation. The delegation is not only the basis for declaring the event, but also an "agreement" that both parties must abide ". OK. Let's improve the above example to further exert the event power.

Imagine a situation where the building has a total of seven floors, and the fire prevention on each layer is good. As long as the fire is not so big, there is no need to let everyone out-which layer is on fire, which layer of employees are evacuated. There is also a fire level problem: we divide the fire size into three levels --

Class C (fire): lighter-grade. My brother on the Left prefers to smoke. Generally, I don't run when I smoke.

Level B (moderate fire): relatively large, requiring the evacuation of personnel on the floor.

A level (fire): Generally, my girlfriend's temper is at this level, and the whole building is required to be evacuated.

OK. Let's look at the Code:

// ===================== The true meaning of Water ====================
//
// Http://blog.csdn.net/FantasiaX
//
// ============ Good deeds, good deeds, silent deeds ==============
Using system;
Using system. Collections. Generic;
Using system. text;

Namespace eventsample
{
// Event parameter class: records the fire floor and level
Class fireeventargs
{
Public int floor;
Public char firelevel;
}

// Delegation is the basis of the event and the "Agreement" that the sender and receiver of the notification comply"
Delegate void firealarmdelegate (Object sender, fireeventargs E );

// Building (class)
Class Building
{
// Declare an event: the event is based on delegation.
Public event firealarmdelegate firealarmring;

// Fire in the building, resulting in fire alarms
Public void onfire (INT floor, char level)
{
Fireeventargs E = new fireeventargs ();
E. Floor = floor;
E. firelevel = level;
This. firealarmring (this, e );
}
Public String buildingname;
}

// Employee (class)
Class employee
{
Public String workingplace;
Public int workingfloor;
// This is the employee's response to the fire event, that is, the employee's event handler. Pay attention to the matching with the delegate.
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 ...");
}
}
}

// Fireman (class)
Class fireman
{
// This is the fireman's response to the fire event, that is, the fireman's event handler. Pay attention to the matching with the delegate.
Public void rushintofire (Object sender, fireeventargs E)
{
Console. writeline ("fighting with fire ...");
}
}

Class Program
{
Static void main (string [] ARGs)
{
Building Sigma = new building ();
Employee Employee = new employee ();
Fireman fireman = new fireman ();

Sigma. buildingname = "Sigma ";
Employee. workingplace = "Sigma ";
Employee. workingfloor = 1;

// The influencer of the event subscribes to the event and starts to care that the event has not occurred.
Sigma. firealarmring + = new firealarmdelegate (employee. Runaway );
Sigma. firealarmring + = new firealarmdelegate (fireman. rushintofire );

// You will set fire!
Console. writeline ("Please input 'fire' to fire the building ...");
String STR = console. Readline ();
If (Str. toupper () = "fire ")
{
Sigma. onfire (7, 'C ');
}
}
}
}
Let's analyze the above Code carefully:

1. in this example, a class fireeventargs class is added, this class is specifically used to pass parameters for the "fire" incident-please go back and look at the "events in the real world" section-we are mainly concerned with the location of fire and the level of fire, because we have two member variables in this class.

2. the subsequent delegation also changed from no parameter to two parameters-object sender and fireeventargs E. You may ask: Why do you need to write two parameters instead of three or four? Mm ...... Traditional habits are like this. The beginning of this tradition should be traced back to the Win32 era of VC-at that time, the message transmission parameters were lparam and wparam, different kinds of useful information are carried. VB imitates them. One is called sender, and the other is called E. Then C # inherits VB and you can see it. As for why the first parameter is of the object type, some "polymorphism" knowledge is needed to be explained. I will not talk about it here. I will take it as an example in "Deep down on Polymorphism. The second parameter uses a self-made class that carries two useful information, as mentioned above.

3. in the onfire method function of the building class, parameters are passed-you can fully understand that the building class treats these parameters (one is this, that is, yourself, and the other is E, it carries important information) and sends it to the receiver, that is, to the class that cares about/subscribes to this event. In our example, the objects subscribed to the building events are employee and fireman, and they will be notified when the events occur, and filter the content that you care about from the event parameters passed to them. This filtering is done by programmers. In this example, the employee filters messages, while the fireman class does not, when you see the fire, it's off (I'm a little worried about my brother on the left ).

4. note: The building class has a buildingname field. Because building is the event owner, it is also the message sender when the event is triggered, this buildingname domain will also be sent along with this. If you understand what polymorphism is, OK, you will understand why you can use building fireplace = (Building) sender; to read this buildingname.

5. The employee class is the most interesting class in this program. It not only provides an impact on build events, but also intelligently filters events-only when the building alarm that you are working on is triggered, in addition, the fire on the floor where you are located or the fire is large enough to evacuate. Carefully analyze the public void runaway (Object sender, fireeventargs e) method.

6. Unlike the employee class, fireman class does not filter events-you think, fire suppression is the responsibility of firefighters, and they will go forward wherever they are on fire!

7. enter the main program and the code is quite clear-indeed, the code of the basic class library is always complicated (in this example, the basic class library refers to the building, employee, fireman classes ). Generally, the source code of the basic class library is not open to the developers of the main program, but is issued as a DLL (assembly) file, therefore, in actual development, the entire program looks very clear.

8. Sigma. firealarmring + = new firealarmdelegate (employee. Runaway );
Sigma. firealarmring + = new firealarmdelegate (fireman. rushintofire );
What can you tell from these two sentences? Oh, because events are based on delegation, they are also multicast! If you do not understand what multicast delegation is, see delegation in simple terms.

9. Because employees work at 1f, Class C fire on Layer 7 will not cause evacuation-only Firefighters will respond.

 

 

To be continue

 

 

Legal disclaimer:This article is protected by intellectual property law. If any organization or individual needs to repost this article, it must ensure the integrity of the article (any omission or modification without the permission of the author shall be deemed as an infringement ). If you need to reprint the document, be sure to indicate the source of the articleCsdnTo protect the rights and interests of the website, please note that the author of the article isLiu tiemengAnd sends an email to the bladey@tom.com indicating the location and purpose of the article. Please repost this legal statement when reprinting. Thank you!

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.