1 namespace DelegateDemo
2 {
3 delegate void HeaterDelegate(int t);
4
5 class Heater
6 {
7 private int temperature;
8 // 烧水
9 //给委托heaterDel加上事件修饰符
10 //event:事件,事件:是被event关键字修饰的委托变量,被event关键字修饰的委托变量,在类的外部只能出现在+=的左侧。也就是只能在类的外部被挂载方法,而不能直接调用
11 public event HeaterDelegate heaterDel;
12
13 public void BoilWater()
14 {
15 for (int i = 0; i <= 100; i++)
16 {
17 temperature = i;
18 if (i >= 90)
19 {
20 if (heaterDel != null)
21 {
22 heaterDel(temperature);
23 }
24 }
25 }
26 }
27 }
28 abstract class LongXia
29 {
30 public abstract void Tongzhi(int t);
31 }
32 class Longzi:LongXia
33 {
34 string name;
35 public Longzi(string n)
36 {
37 name = n;
38 }
39 Display d = new Display();
40 public override void Tongzhi(int wendu)
41 {
42 d.ShowMsg(wendu, name);
43 }
44 }
45 class Display
46 {
47 public void ShowMsg(int param, string n)
48 {
49 Console.WriteLine("Display:水已烧开,当前温度:{0}度。{1}同志", param, n);
50 }
51 }
52 class Alarm
53 {
54 public void MakeAlert(int param, string who)
55 {
56 Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:{1}同志", param, who);
57 }
58 }
59 class Xiazi:LongXia
60 {
61 private string name;
62 Alarm a = new Alarm();
63 public Xiazi(string n)
64 {
65 this.name = n;
66 }
67 public override void Tongzhi(int wendu)
68 {
69 a.MakeAlert(wendu, name);
70 }
71 class Program
72 {
73
74 //////////////////////////////////////////////
75
76 static void Main(string[] args)
77 {
78 Longzi xiaoluobutou = new Longzi("萝卜头");
79 Longzi luobutou = new Longzi("萝卜头");
80
81 Xiazi xia = new Xiazi("看不见");
82
83 Heater h = new Heater();
84
85
86
87 //h.heaterDel = xiaoluobutou.Tongzhi;
88 h.heaterDel += xiaoluobutou.Tongzhi;
89 h.heaterDel += luobutou.Tongzhi;
90 h.heaterDel += xia.Tongzhi;
91
92
93 h.BoilWater();
94
95 //存在在热水器外面调用通知的可能的问题得到解决。
96 h.heaterDel(100);
97 }
98 }
99 }
100 }