e心e意

导航

C# 事件

namespace delegateandEvent
{
//热水器
class Program
{
public class Heater
{
private int temperature;
public delegate void BoilHandler(int param);
public event BoilHandler BoilEvent;
//烧水
public void BoilWater()
{
for (int i = 0; i <= 100; i++)
{
temperature = i;
if (temperature > 95)
{
if (BoilEvent != null)
{
BoilEvent(temperature);
}
}
}
}
}
//报警器
public class Alarm
{
public void MakeAlert(int param)
{
Console.WriteLine("Alarm:滴滴滴,水已经{0}度了:",param);
}
}
//显示器
public class Display
{
public static void showMsg(int param)
{
Console.WriteLine("Display:水快烧开了,当前的水温度:{0}度。",param );
}
}
static void Main(string[] args)
{
Heater heater = new Heater();
Alarm alarm = new Alarm();

heater.BoilEvent += alarm.MakeAlert;//注册方法
heater.BoilEvent += (new Alarm()).MakeAlert;//给匿名对象注册方法
heater.BoilEvent += Display.showMsg;//注册静态方法

heater.BoilWater();//烧水,会自动调用注册过的对象的方法
Console.ReadKey();
}
}
}

posted on 2014-11-26 16:35  e心e意  阅读(78)  评论(0)    收藏  举报