0
点赞
收藏
分享

微信扫一扫

c# 委托,事物



在最外面(命名空间)定义delegete

然后写一个类,使用delegate

再写一个类,用来编写要实现的功能

最后写main。

 

一个热水器代码,用观察者模式,利用委托,事务写出来

class Heater   //加热器
{
private int temperature; //声明温度
public delegate void BoilHandler(int temp); //声明委托
public event BoilHandler bhEvent; //声明事务 public void BoilWater() //烧水
{
for (int i = 0; i < 100;i++ )
{
temperature = i;
if (i > 95)
{
if (bhEvent != null) //如果事务不为空
{
bhEvent(i); //调用事务
}
}
}
} public void Alarm(int temp) //警报功能
{
Console.WriteLine("声音:警报,当前温度{0}",temp);
} public void Display(int temp) //显示功能
{
Console.WriteLine("显示:提示,当前温度{0}",temp);
} }
class Program
{
static void Main(string[] args)
{
Heater heater = new Heater();
heater.bhEvent += heater.Alarm; //给事务注册方法
heater.bhEvent += heater.Display; //给事务注册方法
heater.BoilWater(); //之行烧水的方法,此时就会自动调用警报功能和显示功能
}
}

举报

相关推荐

0 条评论