- /*
- * 使用一个 热水器为 参考物
- */
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Delegate
- {
- // 热水器
- public class Heater
- {
- private int temperature; // 温度
- public delegate void BoilHadler(ing param); // 声明委托 --- 煮水
- public event BoilHandler BoilEvent; // 声明事件
- // 烧水
- public void BoilWater()
- {
- int high_tempera = 100;
- for(int i=0;i<=high_tempera;i++)
- {
- temperature = i;
- if(temperature > 90) // 如果需要再精确点的话,建议你参考物理知识。
- {
- if(BoilEvent != null) // 如果有对象注册
- {
- BoilEvent(temperature);
- }
- }
- }
- }
- }
- // 警报器
- public class Alarm
- {
- public void MakeAlert(ing param)
- {
- Console.WriteLine("Alarm: 滴滴滴......水已经{0} ℃ 了。",param);
- }
- }
- // 温度计
- public class Dispaly
- {
- public static void ShowMsg(ing param)
- {
- Console.WriteLine("Dispaly: 水快烧开了,当期温度 : {0} ℃ . ",param);
- }
- }
- // 入口
- class Program
- {
- 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(); // 烧水开始。
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/2801201614500.html
来源: http://www.codesnippet.cn/detail/2801201614500.html