Event
When other classes or objects are concerned, classes or objects can notify them through events. The class for sending (or triggering) events is called "publisher", and the class for receiving (or processing) events is called "subscription ".
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}
Private void form1_load (Object sender, eventargs E)
{
}
Private void button#click (Object sender, eventargs E)
{
Car car = new car ();
Car. onoilwarning + = new oileventhandler (oilwarning); // associate events
Car. filloil (5 );
Car. startup ();
}
Public void oilwarning (Object sender, oileventargs E)
{
MessageBox. Show ("abnormal car fuel volume detected. Current fuel volume:" + E. oilmass );
}
}
// Event proxy, which can be understood as the content to be transmitted by this event
// We use the self-written oileventargs for event parameters
Public Delegate void oileventhandler (Object sender, oileventargs E );
// Event parameters
Public class oileventargs: system. eventargs
{
Private int _ oilmass = 0; // volume of oil
Public int oilmass
{
Get
{
Return _ oilmass;
}
}
Public oileventargs (INT oilmass)
{
_ Oilmass = oilmass;
}
}
// Automobile, including event members
// When a car is started, if the fuel volume is less than a certain value, the event will be triggered.
Public class car
{
Private int _ oilmass = 0; // volume of oil
Public event oileventhandler onoilwarning; // defines the event member. The event name is onoilwarning.
// Refuel the car
Public void filloil (INT oilmass)
{
_ Oilmass = oilmass;
}
// Start the car
Public void startup ()
{
If (_ oilmass <10)
{
Onoilwarning (this, new oileventargs (_ oilmass ));
}
}
}
[Reprinted From http://tech.ddvip.com/2009-04/1240034523115739.html]