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

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

问题描述

我只是好奇什么是简单的甚至是好的。
我可以有:

 事件EventHandler blah; 

  delegate void Blah(); 
事件Blah Blah1;

除了省去额外的代码,使用EventHandlers还有一些优势吗?谢谢。

解决方案

一个 EventHandler 是一个委托与一些额外的参数。第一个是发件人,即导致该事件的对象,第二个是额外的事件数据。这仅仅是一种有助于声明事件的模式。没有通过发件人作为参数,您不能轻易地检测到哪个对象导致它,这可能导致不必要的重复(复制和粘贴)代码。如果您遵循标准事件模式,您的事件处理程序可以根据导致事件的对象的属性进行不同的任务。



此外,某些事件还会附加额外的信息沿着它们,例如,键入的事件 MouseEventHandler 将在其第二个参数( MouseEventArgs )中传递鼠标指针的位置,为您的事件处理程序消费。这个模式的好处是,如果事件处理程序是通用的,并且不需要它,你可以忽略辅助数据。您可以将 EventHandler 签名的方法连接到 MouseEventHandler 事件,例如(因为第二个参数继承自 EventArgs )。


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

event EventHandler blah;

or

delegate void Blah();
event Blah Blah1;

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

解决方案

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.

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和delegete之间的区别void()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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