自定义EventHandler与EventHandler< EventArgs> [英] Custom EventHandler vs. EventHandler<EventArgs>

查看:129
本文介绍了自定义EventHandler与EventHandler< EventArgs>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在想知道这段代码之间是否有显着差异:

  public event EventHandler&MyEventArgs> SomeEvent; 

而这一个:

  public delegate void MyEventHandler(object sender,MyEventArgs e); 
public event MyEventHandler SomeEvent;

他们都做同样的事情,我无法说出任何区别。
虽然我注意到.NET Framework的大多数类为他们的事件使用了一个自定义事件处理程序委托。这是否有特定的原因?

解决方案

你是对的;他们做同样的事情。因此,您应该更喜欢前者,因为它更清晰,需要更少的输入。



许多.NET Framework类都有自己的自定义事件处理程序代表是因为在2.0版本中引入了泛型(允许缩写语法)之前写的。例如,几乎所有的WinForms库都是在泛型之前编写的,而在那些日子里,后一种形式是只有的方式。


Recently I've been wondering if there is any significant difference between this code:

public event EventHandler<MyEventArgs> SomeEvent;

And this one:

public delegate void MyEventHandler(object sender, MyEventArgs e);
public event MyEventHandler SomeEvent;

They both do the same thing and I haven't been able to tell any difference. Although I've noticed that most classes of the .NET Framework use a custom event handler delegate for their events. Is there a specific reason for this?

解决方案

You're right; they do the same thing. Thus, you should probably prefer the former over the latter because it's clearer and requires less typing.

The reason that lots of the .NET Framework classes have their own custom event handler delegates is because they were written before generics (which allowed the shorthand syntax) were introduced in version 2.0. For example, almost all of the WinForms libraries were written before generics, and back in those days, the latter form was the only way of doing things.

这篇关于自定义EventHandler与EventHandler&lt; EventArgs&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆