事件是构建在委托上的,例如定义Button的Click事件:
public event EventHandler Click;
需要event关键字和EventHandler委托,EventHandler在这里的作用就好像接口,所有想接收事件通知的实例必须实现符合EventHandler参数定义和返回值定义的回调函数,.NET框架通过委托这种方式保证了回调函数类型的安全。
再来看委托的定义,以EventHandler为例:
public delegate void EventHandler(object sender, EventArgs e);
很像方法的定义,只是多了一个delegate关键字;不过它实际上是一个类,可以查看IL代码:
.class public auto ansi serializable sealed EventHandler
extends System.MulticastDelegate
{
.custom instance void System.Runtime.InteropServices.ComVisibleAttribute::.ctor(bool) = { bool(true) }
.method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed
{
}
.method public hidebysig newslot virtual instance class System.IAsyncResult BeginInvoke(object sender, class System.EventArgs e, class System.AsyncCallback callback, object 'object') runtime managed
{
}
.method public hidebysig newslot virtual instance void EndInvoke(class System.IAsyncResult result) runtime managed
{
}
.method public hidebysig newslot virtual instance void Invoke(object sender, class System.EventArgs e) runtime managed
{
}
}
extends System.MulticastDelegate
{
.custom instance void System.Runtime.InteropServices.ComVisibleAttribute::.ctor(bool) = { bool(true) }
.method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed
{
}
.method public hidebysig newslot virtual instance class System.IAsyncResult BeginInvoke(object sender, class System.EventArgs e, class System.AsyncCallback callback, object 'object') runtime managed
{
}
.method public hidebysig newslot virtual instance void EndInvoke(class System.IAsyncResult result) runtime managed
{
}
.method public hidebysig newslot virtual instance void Invoke(object sender, class System.EventArgs e) runtime managed
{
}
}
类中除了构造函数还有三个方法,构造函数接收接收两个参数,一个对象引用和一个指向回调函数的整数,在运行时,EventHandler通过Invoke方法找到对应对象的对应方法(也就是回调函数)执行具体操作。(EventHandler继承自System.MulticastDelegate,在李建忠译的框架程序设计那本书中说MulticastDelegate中含有一个_prev字段使委托可以构成链表实现多播,不过在.NET2.0中查看代码没有看到,也没有详细研究,不过这本书里把.NET1.1中的事件和委托讲的非常透彻,极力推荐)