public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(Object sender, EventArgs e) { Heater heater = new Heater(); Alarm alarm = new Alarm(); //注册方法 heater.Boiled += alarm.MakeAlert; //给匿名对象注册方法 heater.Boiled += (new Alarm()).MakeAlert; heater.Boiled += new Heater.BoiledEventHandler(alarm.MakeAlert); //注册静态方法 heater.Boiled += Display.ShowMsg; //烧水,自动调用注册过对象的方法 heater.BoileWater(); } } public class Heater { private int temperature; //添加型号作为演示 public string type = "RealFire 001"; //添加出产地作为演示 public string area = "China Xian"; //声明委托 public delegate void BoiledEventHandler(Object sender, BoiledEventArgs e); //声明事件 public event BoiledEventHandler Boiled; //定义BoiledEventArgs类,传递给Observer所感兴趣的信息 public class BoiledEventArgs : EventArgs { public readonly int temperature; public BoiledEventArgs(int temperature) { this.temperature = temperature; } } //可以供继承自Heater的类重写,以便继承类拒绝其他对象对它的监视 protected virtual void OnBoiled(BoiledEventArgs e) { //如果有对象注册,调用所有注册对象的方法 if (Boiled != null) Boiled(this, e); } //烧水 public void BoileWater() { for (int i = 0; i <= 100; i++) { temperature = i; if (temperature > 98) { //建立BoiledEventArgs对象 BoiledEventArgs e = new BoiledEventArgs(temperature); //调用OnBoiled方法 OnBoiled(e); } } } } //警报器 public class Alarm { public void MakeAlert(Object sender, Heater.BoiledEventArgs e) { Heater heater = (Heater)sender; MessageBox.Show(string.Format("Alarm:{0}-{1}", heater.area, heater.type)); MessageBox.Show(string.Format("Alarm:水已经{0}度了", e.temperature)); } } //显示器 public class Display { public static void ShowMsg(Object sender, Heater.BoiledEventArgs e) { Heater heater = (Heater)sender; //访问sender中的公共字段 MessageBox.Show(string.Format("Display:{0}-{1}", heater.area, heater.type)); MessageBox.Show(string.Format("Display:水快烧开了,当前{0}度", e.temperature)); } }