using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 委托 { //热水器 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 BoilWater() { for (int i = 0; i <= 100; i++) { temperature = i; if (temperature > 95) { //建立BoiledEventArgs对象 BoiledEventArgs e = new BoiledEventArgs(temperature); OnBoiled(e);//调用OnBolied方法 } } } } //警报器 public class Alarm { public void MakeAlert(object sender, Heater.BoiledEventArgs e) { Heater heater = (Heater)sender; //访问sender中的公共字段 Console.WriteLine("Alarm:{0} - {1}: ", heater.area,heater.type); Console.WriteLine("Alarm:滴滴滴,水已经 {0} 度了;", e.temperature); Console.WriteLine(); } } //显示器 public class Display { public static void ShowMsg(object sender, Heater.BoiledEventArgs e) { Heater heater = (Heater)sender; Console.WriteLine("Display:{0} - {1}: ", heater.area, heater.type); Console.WriteLine("Display:水快烧开了,当前温度: {0} 度。", e.temperature); Console.WriteLine(); } } class Program { static void Main(string[] args) { Heater heater = new Heater(); Alarm alarm = new Alarm(); heater.Boiled += alarm.MakeAlert;//注册方法 heater.Boiled += Display.ShowMsg;//注册静态方法 heater.BoilWater();//烧水,会自动调用注册过对象的方法 } } }
简述委托:
1.委托是一个类,它定义了方法的类型,使得可以将方法当做另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,同时使程序具有更好的可扩展性。原文地址:http://blog.csdn.net/ry513705618/article/details/41418171