自定义 EventHandler 与 EventHandler

发布于 2024-12-23 11:15:08 字数 348 浏览 1 评论 0原文

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

public event EventHandler<MyEventArgs> SomeEvent;

和这段代码:

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

它们都做同样的事情,但我无法分辨出任何区别。 尽管我注意到 .NET Framework 的大多数类都为其事件使用自定义事件处理程序委托。这有什么具体原因吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼藏柔 2024-12-30 11:15:08

你说得对;他们做同样的事情。因此,您可能应该更喜欢前者而不是后者,因为它更清晰并且需要更少的打字。

许多 .NET Framework 类都有自己的自定义事件处理程序委托的原因是,它们是在 2.0 版中引入泛型(允许简写语法)之前编写的。例如,几乎所有 WinForms 库都是在泛型之前编写的,而在当时,后一种形式是唯一的处理方式。

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.

不打扰别人 2024-12-30 11:15:08

第二种方式提供了更大的灵活性和类型安全性。对应签名的方法较少 =>犯错误的地方就少了。自定义委托允许准确指定您需要的参数(或不指定任何参数) - 没有发送者 + 参数货物邪教。

The second way gives more flexibility and type safety. There are less methods with corresponding signature => less place for a mistake. Custom delegate allows to specify exactly parameters you need (or specify no one) - no sender+args cargo cult.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文