一个人(people),在他60岁之后,就宣布进入晚年了,在这个期间要多注意身体,多体检。
namespace NET基础才是重中之重 { /// <summary> /// 人类 /// </summary> public class People { private int age; public string name = "张占占"; //姓名 public string gander = "男"; // 性别 #region 构造方法 public People(string _name, string _gander) { name = _name; gander = _gander; } public People() { } #endregion //声明委托 public delegate void LifedEventHandler(Object sender, LifedEventArgs e); public event LifedEventHandler Liefd; //声明事件 /// <summary> /// 定义LifedEventArgs类 /// 传递给Observer所感兴趣的信息 /// </summary> public class LifedEventArgs : EventArgs { public readonly int temperature; public LifedEventArgs(int age) { this.temperature = age; } } /// <summary> /// 可以供继承自 People 的类重写 /// 以便继承类拒绝其他对象对它的监视 /// </summary> /// <param name="e"></param> protected virtual void OnLife(LifedEventArgs e) { if (Liefd != null) { Liefd(this, e); // 调用所有注册对象的方法 } } /// <summary> /// 生活 /// </summary> public void Life() { for (int i = 0; i <= 70; i++) { age = i; if (age > 60) { LifedEventArgs e = new LifedEventArgs(age); OnLife(e); } } } } /// <summary> /// 警报您了 /// </summary> public class Alarm { public void MakeAlert(Object sender, People.LifedEventArgs e) { People heater = (People)sender; //访问 sender 中的公共字段 Console.WriteLine("Alarm:{0} - {1}: ", heater.gander, heater.name); Console.WriteLine("Alarm: 您已经 {0} 岁了:", e.temperature); Console.WriteLine(); } } /// <summary> /// 显示信息 /// </summary> public class Display { public static void ShowMsg(Object sender, People.LifedEventArgs e) { //静态方法 People heater = (People)sender; Console.WriteLine("Display:{0} - {1}: ", heater.gander, heater.name); Console.WriteLine("Display:您已经进行晚年了,{0}岁要注意身体了。", e.temperature); Console.WriteLine(); } } class Program { static void Main() { People heater = new People("张占占", "男"); Alarm alarm = new Alarm(); heater.Liefd += alarm.MakeAlert; //注册方法 heater.Liefd += Display.ShowMsg; //注册静态方法 heater.Life(); //会自动调用注册过对象的方法 Console.ReadKey(); } } }
本文转自博客园张占岭(仓储大叔)的博客,原文链接:基础才是重中之重~通过人类的生活来学习Delegate,如需转载请自行联系原博主。