庖丁解牛看委託和事件(續)
阿新 • • 發佈:2022-05-04
上一篇文章:庖丁解牛——深入解析委託和事件之後,以一題面試題來總結事件
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 }); } } } } } }