事件的例子
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication1 { public delegate void SalaryCompute(object sender, MyEventArgs e); //声明一个代理类 public class Employee { public event SalaryCompute OnSalaryCompute; //定义事件,将其与代理绑定 public virtual void FireEvent(MyEventArgs e) //触发事件的方法 { if (OnSalaryCompute != null) { OnSalaryCompute(this, e); //触发事件 } } } public class MyEventArgs : EventArgs //定义事件参数类 { public readonly double _salary; public MyEventArgs(double salary) { this._salary = salary; } } public class HumanResource { public void SalaryHandler(object sender, MyEventArgs e) //事件处理函数,其签名应与代理签名相同 { Console.WriteLine("Salary is {0}", e._salary); //只是打印一行字而已 } public static void Main() { Employee ep = new Employee(); HumanResource hr = new HumanResource(); MyEventArgs e = new MyEventArgs(123.40); ep.OnSalaryCompute += new SalaryCompute(hr.SalaryHandler); //将打印一行文字的方法注册到事件中 for (; ; ) { Thread.Sleep(1000); //让程序“睡”一秒 ep.FireEvent(e); //触发事件 } //Console.Read(); } } }