Understand examples of events and delegation in C #

Source: Internet
Author: User

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]

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.