C# 事件和委托
1 public class Heater {
2 private int temperature;
3 public string type = "RealFire 001"; // 添加型號作為演示
4 public string area = "China Xian"; // 添加產(chǎn)地作為演示
5 //聲明委托
6 public delegate void BoiledEventHandler(Object sender, BoiledEventArgs e);
7 public event BoiledEventHandler Boiled; //聲明事件
8
9 // 定義BoiledEventArgs類,傳遞給Observer所感興趣的信息
10 public class BoiledEventArgs : EventArgs {
11 public readonly int temperature;
12 public BoiledEventArgs(int temperature) {
13 this.temperature = temperature;
14 }
15 }
16
17 // 可以供繼承自 Heater 的類重寫,以便繼承類拒絕其他對象對它的監(jiān)視
18 protected virtual void OnBoiled(BoiledEventArgs e) {
19 if (Boiled != null) { // 如果有對象注冊
20 Boiled(this, e); // 調(diào)用所有注冊對象的方法
21 }
22 }
23
24 // 燒水。
25 public void BoilWater() {
26 for (int i = 0; i <= 100; i++) {
27 temperature = i;
28 if (temperature > 95) {
29 //建立BoiledEventArgs 對象。
30 BoiledEventArgs e = new BoiledEventArgs(temperature);
31 OnBoiled(e); // 調(diào)用 OnBolied方法
32 }
33 }
34 }
35 }
36
37 // 警報器
38 public class Alarm {
39 public void MakeAlert(Object sender, Heater.BoiledEventArgs e) {
40 Heater heater = (Heater)sender; //這里是不是很熟悉呢?
41 //訪問 sender 中的公共字段
42 Console.WriteLine("Alarm:{0} - {1}: ", heater.area, heater.type);
43 Console.WriteLine("Alarm: 嘀嘀嘀,水已經(jīng) {0} 度了:", e.temperature);
44 Console.WriteLine();
45 }
46 }
47
48 // 顯示器
49 public class Display {
50 public static void ShowMsg(Object sender, Heater.BoiledEventArgs e) { //靜態(tài)方法
51 Heater heater = (Heater)sender;
52 Console.WriteLine("Display:{0} - {1}: ", heater.area, heater.type);
53 Console.WriteLine("Display:水快燒開了,當前溫度:{0}度。", e.temperature);
54 Console.WriteLine();
55 }
56 }
定義委托,事件是委托的對象,事件對類外暴露,以供其他類調(diào)用。
protect修飾符,僅限類和派生類訪問。
轉(zhuǎn)載于:https://www.cnblogs.com/slarkleoric/p/6833012.html
總結(jié)
- 上一篇: java 加解密
- 下一篇: CentOS6.8 搭建SVN并用钩子自