很容易理解事件委托(转)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 namespace Delegate
2 {
3 // 热水器
4 public class Heater
5 {
6 private int temperature;
7 public delegate void BoilHandler(int param); //声明委托
8 public event BoilHandler BoilEvent; //声明事件
9
10 // 烧水
11 public void BoilWater()
12 {
13 for (int i = 0; i <= 100; i++)
14 {
15 temperature = i;
16
17 if (temperature > 95)
18 {
19 if (BoilEvent != null)
20 { //如果有对象注册
21 BoilEvent(temperature); //调用所有注册对象的方法
22 }
23 }
24 }
25 }
26 }
27
28 // 警报器
29 public class Alarm
30 {
31 public void MakeAlert(int param)
32 {
33 Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:", param);
34 }
35 }
36
37 // 显示器
38 public class Display
39 {
40 public static void ShowMsg(int param)
41 { //静态方法
42 Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", param);
43 }
44 }
45
46 class Program
47 {
48 static void Main()
49 {
50 Heater heater = new Heater();
51 Alarm alarm = new Alarm();
52
53 heater.BoilEvent += alarm.MakeAlert; //注册方法
54 heater.BoilEvent += (new Alarm()).MakeAlert; //给匿名对象注册方法
55 heater.BoilEvent += Display.ShowMsg; //注册静态方法
56
57 heater.BoilWater(); //烧水,会自动调用注册过对象的方法
58 }
59 }
60
61 }