开发者

Difference between EventHandler and delegate void()

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

event EventHandler blah;

or

delegate void Blah(开发者_如何学C);
event Blah Blah1;

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


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).


Your delegate won't give any indication of what's raised the event - there's no equivalent to the "sender".

Additionally, if you implement a handler with a signature of:

void Handler(object sender, EventArgs e)

then that can handle any event following the normal pattern, due to delegate variance. So even if you don't need any information from the event argument, you can still subscribe to (say) the Control.KeyPress event.

Now, if all events follow the same pattern, that one handler may be usable for multiple events - but you couldn't use it to handle an event with a delegate type of Action (which is basically what your delegate type corresponds to - there's no need to declare a new one).

EDIT: Given your comment, I feel I should point out that your question doesn't really cover the differences between events and delegates - it covers the difference between using a "standard" delegate type for events, and using a "custom" delegate type for events. The difference between delegates and events is really about encapsulation. I have an article which you may find useful - although it covers largely the same ground as C# in Depth.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜