EventHandler和委托void()之间的区别 [英] Difference between EventHandler and delegate void()

查看:76
本文介绍了EventHandler和委托void()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇简单的evenhandler到底有什么用. 我可以拥有:

I am just curious what exactly is simple evenhandler good for. I can have:

event EventHandler blah;

delegate void Blah();
event Blah Blah1;

除了节省额外的代码行之外,使用EventHandlers是否还有其他优势?

Is there some advantage of using EventHandlers except sparing an extra line of code?

推荐答案

EventHandler是具有几个额外参数的delegate.第一个是发送者,即导致该事件的对象,第二个是额外的事件数据.这只是用于声明事件的一致模式.如果不将发送方作为参数传递,则您将无法轻易检测出导致它的对象,这可能会导致不必要的重复(复制粘贴)代码.如果遵循标准事件模式,则事件处理程序可以根据导致事件的对象的属性来执行不同的任务.

An EventHandler is a delegate with a couple extra parameters. The first one is the sender, that is, the object that caused that event and the second is extra event data. It's simply a consistent pattern useful for declaring events. Without passing the sender as an argument, you cannot easily detect which object caused it and this might result in unnecessarily duplicated (copy-and-pasted) code. If you follow the standard event pattern, your event handler can carry on different tasks based on a property of the object that caused the event.

此外,某些事件还携带其他信息,例如,键入MouseEventHandler的事件将在其第二个参数(MouseEventArgs)中传递鼠标指针的位置,以供事件处理程序使用.这种模式的好处是,如果您的事件处理程序是通用的并且不需要它,则可以忽略辅助数据.例如,您可以将具有EventHandler签名的方法连接到MouseEventHandler事件(因为第二个参数的类型继承自EventArgs).

Besides, some events carry extra information along them, for example an event typed MouseEventHandler will pass the location of the mouse pointer in its second argument (MouseEventArgs) for your event handler to consume. The good thing about this pattern is that you can ignore the auxiliary data if your event handler is general and doesn't need it. You are able to hook up a method with EventHandler signature to a MouseEventHandler event, for example (since the type of the second argument inherits from EventArgs).

这篇关于EventHandler和委托void()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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