在咱們作工業軟件中,常常會遇到要實時監控某一點,在這個點變化時去作一些事情測試
放入程序裏呢,就是要實時監控某一屬性的值,當值發生變化時觸發事件,其核心就是藉助屬性的Set方法,來判斷當前set的值是否與原來的值相等,若是相等直接賦值不予理會,若是不相等,說明值變了,根據本身調用的方法,聲明委託,事件,觸發方法this
核心代碼:spa
public delegate void tempChange(object sender,EventArgs e); public event tempChange onTempChange; private bool _temp= false; public bool Temp { get { return _temp; } set { if (_temp!=value) { onTempChange(new object(), new EventArgs()); } _temp= value;
}
}
下邊咱們作一個Demo ,來測試一下code
咱們新建一個from,上邊添加一個lable,添加一個button 咱們經過button來改變這個temp屬性的值 ,使之觸發對應的事件orm
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } int i = 0; private void Form1_Load(object sender, EventArgs e) { changeEvent += Form1_changeEvent; } void Form1_changeEvent(string value) { this.richTextBox1.Invoke(new Action(() => { this.richTextBox1.AppendText("當前lable的值爲" + value+"\r\n"); })); } private void button1_Click(object sender, EventArgs e) { Temp = i + ""; label1.Text = Temp; i++; } public delegate void ChangeDelegate(string value); public event ChangeDelegate changeEvent; public string _temp; public string Temp { get { return _temp; } set { if (_temp != value) { changeEvent(value); } _temp = value; } } } }
測試:blog
能夠看到 咱們每點擊一次按鈕 都改變了temp的值,從而觸發了changeEvent事件 ------給richTextBox添加文本事件