吉吉于

free

C#委托与事件实例

01 using System;
02 namespace z
03 {
04     class Program
05     {
06         public static  void Main()
07         {
08             Heater heater = new Heater();
09             Alarm alarm = new Alarm();
10             heater.BoilEvent += alarm.MakeAlert;
11             heater.BoilEvent += Display.ShowMsg;
12             heater.BoilWater();
13             Console.ReadLine();
14         }
15     }
16     class Heater
17     {
18         private int temperature;
19         public string type = “Lazynight Heater”;
20         public string area = “Made in China.”;
21         public delegate void BoilHandler(Object sender, BoiledEventArgs e);
22         public event BoilHandler BoilEvent;
23         public class BoiledEventArgs : EventArgs
24         {
25             public readonly int temperature;
26             public BoiledEventArgs(int temperature)
27             {
28                 this.temperature = temperature;
29             }
30         }
31         protected void OnBoiled(BoiledEventArgs e)
32         {
33             if (BoilEvent != null)
34             {
35                 BoilEvent(this, e);
36             }
37         }
38         public void BoilWater()
39         {
40             for (int i = ; i <= 100; i++)
41             {
42                 temperature = i;
43                 if (temperature > 95)
44                 {
45                     BoiledEventArgs e = new BoiledEventArgs(temperature);
46                     OnBoiled(e);
47                 }
48
49             }
50         }
51     }
52     class Alarm
53     {
54         public void MakeAlert(object sender, Heater.BoiledEventArgs e)
55         {
56             Heater heater = (Heater)sender;
57             Console.WriteLine(“{0}-{1}”, heater.area, heater.type);
58             if (e.temperature == 100)
59             {
60                 Console.WriteLine(“水开了。”);
61             }
62             else
63             {
64                 Console.WriteLine(“水已经{0}度了。”, e.temperature);
65             }
66         }
67     }
68     class Display
69     {
70         public static void ShowMsg(object sender, Heater.BoiledEventArgs e)
71         {
72             Heater heater = (Heater)sender;
73             if (e.temperature != 100)
74             {
75                 Console.WriteLine(“水快开了,当前温度:{0}”, e.temperature);
76             }
77         }
78     }
79 }

转载请注明:于哲的博客 » C#委托与事件实例