标签:访问 send 字段 play display prot heat and ado
1 public class Heater { 2 private int temperature; 3 public string type = "RealFire 001"; // 添加型号作为演示 4 public string area = "China Xian"; // 添加产地作为演示 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 的类重写,以便继承类拒绝其他对象对它的监视 18 protected virtual void OnBoiled(BoiledEventArgs e) { 19 if (Boiled != null) { // 如果有对象注册 20 Boiled(this, e); // 调用所有注册对象的方法 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); // 调用 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: 嘀嘀嘀,水已经 {0} 度了:", e.temperature); 44 Console.WriteLine(); 45 } 46 } 47 48 // 显示器 49 public class Display { 50 public static void ShowMsg(Object sender, Heater.BoiledEventArgs e) { //静态方法 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 }
定义委托,事件是委托的对象,事件对类外暴露,以供其他类调用。
protect修饰符,仅限类和派生类访问。
标签:访问 send 字段 play display prot heat and ado
原文地址:http://www.cnblogs.com/slarkleoric/p/6833012.html