This article uses an event to simulate the process of water heater burning, which is similar to this:
The water heater starts to heat the water. When the water is heated to more than 95 degrees, the water heater's alarm starts and the current water temperature is displayed on the screen.
It is not difficult to see from the above section that to simulate the program, you need a water Heater object Heater, an Alarm object Alarm, and a Display object.
Let's explain the code below.
/// <Summary>
/// Water heater used for boiling water
/// </Summary>
Class Heater
{
Private int temperature; // Water temperature
Public delegate void BoilEventHandler (object sender, BoilEventArgs e );
Public event BoilEventHandler boil; // custom event
Public void OnBoil (BoilEventArgs e) // execute the event after the water temperature reaches a certain temperature
{
If (boil! = Null)
Boil (this, e );
}
Public void BoilWater () // the water starts to burn from 0 degrees, and an alarm starts when it reaches 95 degrees.
{
For (int I = 0; I <100; I ++)
{
Temperature = I;
If (temperature> = 95)
{
BoilEventArgs e = new BoilEventArgs (temperature );
OnBoil (e );
}
}
}
}
/// <Summary>
/// Custom Event parameters, which must inherit the EventArgs class
/// </Summary>
Class BoilEventArgs: EventArgs
{
Public readonly int temperature; // temperature
Public BoilEventArgs (int temperature)
{
This. temperature = temperature;
}
}
/// <Summary>
/// Alarm class. When the water temperature reaches a certain level, a sound is triggered to indicate that the user's water has been opened.
/// </Summary>
Class Alarm
{
Public void MakeAlarm (object sender, BoilEventArgs e)
{
Console. WriteLine (string. Format ("alarm: doodle, water temperature {0} degree", e. temperature. ToString ()));
}
}
/// <Summary>
/// Display. When the temperature reaches a certain level, the current temperature is displayed on the screen.
/// </Summary>
Class Display
{
Public static void ShowMessage (object sender, BoilEventArgs e)
{
Console. WriteLine (string. Format ("Screen Display: Current temperature {0} degrees", e. temperature. ToString ()));
}
}
Class Program
{
Static void Main (string [] args)
{
Heater heater = new Heater ();
Alarm alarm = new Alarm ();
Heater. boil + = alarm. MakeAlarm;
Heater. boil + = Display. ShowMessage;
Heater. BoilWater ();
Console. ReadLine ();
}
}
Output result: