很多时候我们需要程序具有一种功能,就是当满足某一条件时触发某个动作,使用C#的事件机制就可以达到这个目的下面的例子是一个很好的演示。
这段代码实现了对一个变量的监视,一旦变量发生改变,就触发动作
定义事件类:
1 class Event 2 { 3 public delegate void tempChange(object sender, EventArgs e); 4 public event tempChange OntempChange; 5 string temp; 6 public string Temp 7 { 8 get 9 { 10 return temp; 11 } 12 set 13 { 14 if (temp != value) 15 { 16 OntempChange(this, new EventArgs()); 17 } 18 temp = value; 19 } 20 } 21 }