.Net学习之基于委托、事件的观察者模式
/// <summary> /// 猫类 /// </summary> public class Cat { //委托声明 public delegate void Miaowhandler(Object sender, MiaowEventArgs e); //事件声明 public event Miaowhandler MiaowEvent; private string MiaowStr = string.Empty; //自定义参数信息 public class MiaowEventArgs : EventArgs { public readonly string MiaowStr; public MiaowEventArgs(string miaowStr) { this.MiaowStr = miaowStr; } } //猫叫 public void Miaow() { this.MiaowStr = "瞄瞄瞄瞄瞄瞄~~~~"; Console.WriteLine(this.MiaowStr); } public void OnMiaow(MiaowEventArgs e) { if (MiaowEvent != null) MiaowEvent(this, e); } public void MakeMiaow() { this.MiaowStr = "猫睡着了"; Console.WriteLine(MiaowStr); Thread.Sleep(2000); this.MiaowStr = "猫醒了"; Console.WriteLine("猫醒了"); Thread.Sleep(500); Miaow(); Thread.Sleep(1000); MiaowEventArgs e =new MiaowEventArgs(this.MiaowStr); OnMiaow(e); } }