将委托定义到一个单独的类中
public class ListenerValue{
private int load;
public int Value{
get { return load; }
set {
if (value != load) {
WhenMyValueChange();
}
load = value;
}
}
//定义的委托
public delegate void MyValueChanged(object sender, EventArgs e);
//与委托相关联的事件
public event MyValueChanged OnMyValueChanged;
//事件触发函数
private void WhenMyValueChange() {
if (OnMyValueChanged != null) {
OnMyValueChanged(this, null);
}
}
}
在应用中调用:
public partial class Form1: Form {
// 定义全局变量
ListenerValue listenerValue;
//初始化
public Form1(){
InitializeComponent();
listenerValue = new ListenerValue();
listenerValue.Load = 0;
listenerValue.OnMyValueChanged += ListenerValue_OnMyValueChanged;
}
//在应用中将要监测的变量的值赋给listenerValue.Load
private void Test(){
int test = 1 ;
listenerValue.Load = test ;
}
private void ListenerValue_OnMyValueChanged(object sender, EventArgs e) {
//当变量值发生变化的时候,执行
}
}