庖丁解牛看委托和事件(续)
上一篇文章:庖丁解牛——深入解析委托和事件之后,以一题面试题来总结事件
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace CallChange { public class Call { static void Main(string[] args) { MessageMonitoring mm = new MessageMonitoring(); //添加监听事件的响应函数 mm.OnValueChange += new MMEventHandle((s, e) => { Console.WriteLine(e.Value); }); mm.Run(); } } //参数e public class MMEventArgs : EventArgs { public int Value { get; set; } } public delegate void MMEventHandle(object sender, MMEventArgs e); //信息监控的类,当Value改变的时候,出发事件OnValueChange public class MessageMonitoring { public event MMEventHandle OnValueChange; private int _value; public void Run() { Thread thread = new Thread(() => { while (true) { Thread.Sleep(1000); ++Value; } }); thread.Start(); } //属性改变 public int Value { get { return _value; } set { if (_value != value) { _value = value; if (OnValueChange != null) { OnValueChange(this, new MMEventArgs { Value = _value }); } } } } } }