上篇文章介绍了C#中事件的基本实现方式,在本文中,将对最常见的事件委托EventHandler和EventHandler<T>做介绍。

事实上,在前面文章的介绍中,已经涉及到了EventHandler和EventHandler<T>。在C# 2.0泛型出现之前,EventHandler对C#中最常见的事件处理函数进行了签名定义,它指代了这样一些函数,这些函数没有返回值,有两个参数,第一个参数的类型是object,而第二个参数的类型是EventArgs。

在引入泛型之后,.NET Framework加入了EventHandler<T>委托,与EventHandler不同的是,其第二个参数的类型由T指定,而且该类型必须由EventArgs继承。这一点从下面的定义与泛型约束可以看出。

view plaincopy to clipboardprint?
  1. [Serializable]   
  2. public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e)    
  3. where TEventArgs: EventArgs;  

现在再回过头来看上文中“服务器”的例子,在该例中,我们新定义了一个事件委托“ServerEventHandler”,事实上,在C# 2.0中,我们也可以使用EventHandler<ServerEventArgs>委托,效果是完全相同的,因为“ServerEventHandler”与“EventHandler<ServerEventArgs>”所指代的函数具有相同的签名形式。因此,在定义事件的时候,可以采用下面的形式,这样看上去更为规范:

view plaincopy to clipboardprint?
  1. /// <summary>   
  2. /// 定义一个事件,当服务器正常启动后,触发该事件   
  3. /// </summary>   
  4. public event EventHandler<ServerEventArgs> Started;   
  5. /// <summary>   
  6. /// 定义一个事件,当服务器正常结束后,触发该事件   
  7. /// </summary>   
  8. public event EventHandler<ServerEventArgs> Stopped;   

相关文章:

  • 2021-08-15
  • 2021-11-04
  • 2022-12-23
  • 2021-10-31
  • 2021-06-21
  • 2022-12-23
  • 2022-12-23
  • 2021-11-14
猜你喜欢
  • 2022-12-23
  • 2021-06-17
  • 2021-09-13
  • 2021-07-15
  • 2021-11-07
  • 2021-10-28
  • 2022-03-08
相关资源
相似解决方案