C#委托和事件例子
题目:
一个热水器包括加热水的部分heater、显示屏提示部分display和发出声音报警部分alert,
要求当热水器加热水到95度以上时,display和alert部分都需要分别以各自的方式发出警报。
编程模拟这个过程。
在这里我定义三个类:heater,display和alert;框架结构图如下图所示:
在heater中,定义委托和事件,并将其绑定在一起,其内容如下:
public delegate void boiledhandler(int temp); //定义一个委托(等同于一个类)
class Heater
{
private int temperature;
public event boiledhandler OnBoiled; //定义一个事件,并绑定委托;
public void BoiledWater() //方法
{
for (int i = 0; i <= 100; i++)
{
temperature = i;
if (temperature >= 95)
{
OnBoiled(temperature); //事件触发函数
}
}
}
}
在display类中,其主要定义显示的方法:
class Display
{
public void DispTemp(int temp)
{
Console.WriteLine("现?在¨²水?温?:êo" + temp);
}
}
在alert类中定义方法:
class Alert
{
public void AlertTemp(int temp)
{
Console.WriteLine("嘀¤?嘀¤?嘀¤?,ê?水?温?" + temp + ",快¨¬开a啦¤2!ê?");
}
}
在主函数中调用如下:
class Program
{
static void Main(string[] args)
{
Heater h = new Heater();
Display d = new Display();
Alert a = new Alert();
h.OnBoiled += d.DispTemp; //事件注册
h.OnBoiled += a.AlertTemp; //事件注册
h.BoiledWater();
Console.ReadKey();
}
}
运行结果如下所示: