Detailed description of delegation and Event code and (Object sender, eventargs E)

Source: Internet
Author: User
Tags prototype definition

Delegation and eventsCodeDetails

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace @ delegate // custom namespace, create a console Program , Automatically added after naming
{
// Water Heater
Public class Heater
{
Private int temperature;
Public string type = "realfire 001"; // Add a model for demonstration
Public String area = "China Xian"; // Add the origin as a demo
// Declare the delegate
Public Delegate void boiledeventhandler (Object sender, boiledeventargs E);/* boiledeventhandler is equivalent to a type (delegate), which is equivalent to string, the parameter format declared by it must be the same as the parameter form of the method to be included later, for example, the method in the yellow highlighted part */
// Declare the event
Public event boiledeventhandler boiled;/* boiled is equivalent to encapsulating the boiledeventhandler type objects (variables) so that it is always pravite inside the class, the access permissions of + = and-= are the modifier permissions for declaration */

// define the boiledeventargs class and pass the information to the observer. // Observer design mode
public class boiledeventargs: eventargs
{< br> Public readonly int temperature;
Public boiledeventargs (INT temperature)
{< br> This. temperature = temperature;
}< BR >}

// You can override a class that inherits from heater so that the inherited class rejects other objects from monitoring it. // The virtual method can overwrite and override it in the class.
Protected virtual void onboiled (boiledeventargs E)
{
If (boiled! = NULL)
{// If an object is registered
Boiled (this, e); // call the method of all registered objects
}
}

// Boil water.
Public void boilwater ()
{
For (INT I = 0; I <= 100; I ++)
{
Temperature = I;
If (temperature> 95)
{
// Create a boiledeventargs object.
Boiledeventargs E = new boiledeventargs (temperature );
Onboiled (E); // call the onbolied Method

}
}
}
}

// alarm
public class alarm
{< br> Public void makealert (Object sender, heater. boiledeventargs e)
{< br> heater = (heater) sender; // are you familiar with this?
// access the public field in sender
console. writeline ("alarm: {0}-{1}:", heater. area, heater. type);
console. writeline ("alarm: Tick, water has {0} degrees:", E. temperature);
console. writeline ();
}< BR >}

// display
public class display
{< br> Public static void showmsg (Object sender, heater. boiledeventargs e)
{// static method
heater = (heater) sender;
console. writeline ("display: {0}-{1}:", heater. area, heater. type);
console. writeline ("display: The water is almost burned out. Current temperature: {0. ", E. Temperature);
console. writeline ();
}< BR >}

Class Program
{
Static void main ()
{
Heater heater = new heater ();
Alarm alarm = new alarm ();

Heater. Boiled + = alarm. makealert; // Registration Method
Heater. Boiled + = (new alarm (). makealert; // Method for registering anonymous objects
Heater. Boiled + = new heater. boiledeventhandler (alarm. makealert); // You can also register
Heater. Boiled + = display. showmsg; // register the static method

Heater. boilwater (); // The method of boiling water, which automatically calls the method of registering an object
Console. readkey ();
}
}
}

The event is similar to an encapsulation of the delegate variable:

First, the event is a delegate type variable, so it must be declared inside the class. Because the event itself is a delegate, You can naturally assign the delegate Method to the event.

This (encapsulated delegate) variable is different from the common delegate type variable:

1. Whether you declare it as public or protected, it will always be declared as private during compilation. Therefore, if you directly assign the "=" value to an event, it can only be performed within the class where the event is declared.

2. It encapsulates two operations "+ =" and "-=". The access declarations of public and protected are only for the "+ =" and "-=" operations on it. These two operations are dedicated to registering methods on the client of the class.

If you do not use events and use a public delegate, you can also perform the preceding operations, but the class encapsulation is poor. You can assign values to the delegate variable directly outside the class. The second is that the syntax will be very strange, because the "=" value assignment syntax is used for registering the first method (because it is required to be instantiated ), the second registration method uses the "+ =" and registration syntax.

When using the event, the above two problems are solved. You only need to remember to use "+ =" to register the method.

In fact, the Delegate will indeed be compiled into classes during compilation. Because delegate is a class, delegates can be declared wherever classes can be declared.

 

Knowledge points involved:

Introduction to the Observer Design Mode

The observer design mode includes the following two types of objects:

Subject: A monitoring object, which usually contains content of interest to other objects. In this example, the water heater is a monitoring object, and the content that other objects are interested in is the temprature field. When the value of this field is approaching 100, the data is constantly sent to the object that monitors it.
Observer: The monitor that monitors subject. When something in a subject occurs, it notifies observer, and the observer takes corresponding action.In this example, the observer has an alarm and a monitor, and they take the action of issuing an alarm and displaying the water temperature respectively.
In this example, the sequence of events should be as follows:

The alarm and monitor tell the water heater that it is interested in its temperature (registered ).
The water heater retains reference to alarms and monitors after it is known.
When the water temperature exceeds 95 degrees, the water heater automatically calls the makealert () method of the alarm and the showmsg () method of the monitor by referencing the alarm and display.
There are many examples like this. gof abstracts it and is called the observer design pattern:The observer design mode is used to define a one-to-many dependency between objects, so that when the state of an object changes, other objects dependent on it will be automatically notified and updated.The observer mode is a loosely coupled design mode.

Delegate and event in. NET Framework

. NET Framework encoding specifications:

The name of the delegate type should end with eventhandler.
Prototype definition of the delegate: There is a void returned value, and two input parameters are accepted: an object type, and an eventargs type (or inherited from eventargs ). // Many event processing functions are like this.
The event is named as the part left after the eventhandler is removed by the delegate.
The types inherited from eventargs should end with eventargs.
Next, let's explain:

The parameter of the object type in the delegate declaration prototype represents the subject, that is, the monitoring object. In this example, it is the heater (water heater ). A callback function (such as makealert of alarm) can be used to access the event-triggered object (heater ).
The eventargs object contains the data that the observer is interested in. In this example, It is temperature.
In fact, the above is not only for coding specifications, but also makes the program more flexible. For example, if we not only want to get the temperature of the water heater, but also want to get its production date, model, and price in the observer side (alarm or display) method, the delegation and method declaration will become very troublesome. If we pass the water heater reference to the method of the alarm, we can directly access the water heater in the method.

Summary:

Now let's take a look at the parameters (Object sender, eventargs E) in many function headers)

Object sender

Sender is the event source (Monitored object, also called monitoring object, event trigger. In this example, it is a water heater and the water temperature reaches 95 ℃ or above to trigger the event), which indicates the object that triggers the event.

// For example, if you press the button, the sender is the button that triggers the predefined event processing code, such as onclik.

 

 

Eventargs E

E is an event parameter (*** eventargs class object, which may be of different types depending on the event, but must inherit the eventargs class. For example, the public class boiledeventargs: eventargs in this example, according to the net encoding specification, the types inherited from eventargs should end with eventargs. ", So the name is *** eventargs), which contains information related to the event, such as parameters. This requires you to manually write the code (the encapsulated code can be used directly, but if so, its name is no longer eventargs, but a name ending with eventargs. According. net encoding specification. If eventargs is directly used in a function header, it means that it does not need to use e to pass special parameters. You can check the definition of eventargs in, it is used to help you process events. You can also pass references and directly refer to the class members in the method.

This example contains the parameter temperature.

Public class boiledeventargs: eventargs
{
Public readonly int temperature;
Public boiledeventargs (INT temperature)
{
This. temperature = temperature;
}
}

// If the "click a form with the mouse" event occurs, E contains the clicked position and so on.

Finally, this sender and E and their entire processing method are justAnother manifestation of WINDOWS Message MechanismThat's it!

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.