using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace EventDemo { 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(); } } }
C#中事件的要点:
1)事件的代理类定义
public delegate void SalaryCompute(object sender,MyEventArgs e);
2) 定义事件
public event SalaryCompute OnSalaryCompute;
3 )定义事件参数(可选)
public class MyEventArgs : EventArgs
{
}
4) 定义事件处理函数
hr.SalaryHandler(object sender,MyEventArgs e);
5) 在主函数中事件委托
ep.OnSalarycompute+=new SalaryCompute(hr.SalaryHandler);
6)触发事件
ep.FireEvent(e);
关键点事件代理的方法签名,要与事件处理函数的方法签名一致。
参考链接:
http://www.cnblogs.com/donghaiyiyu/archive/2007/07/29/828738.html