Should EventHandler always be used for events?

十年热恋 提交于 2019-12-21 18:57:36

问题


I've been merrily writing events using custom delegate types and the generic Action delegate type, without really thinking about what I was doing.

I have some nice extension helpers for Action and EventHandler which makes me tend to use those predefined delegate types rather than my own, but aside from that...

Is there a good reason other than convention to favour EventHandler and EventHandler<T> over custom delegate types or generic Action delegate types?


回答1:


The main advantage of the signature EventHandler<T> over using one parameter for each member of your EventArgs is that you can add additional properties to your EventArgs without breaking compatibility.
IMO this is the most important argument. Being able to extent your EventArgs without breaking subscribing code is very nice. But of course you can achieve the same with any signature that uses some kind of property-bag parameter instead of a parameter per property.

Then there is variance, EventHandler<Base> is convertible to EventHander<Derived>, so you can write an EventHandler with parameter EventArgs and it can subscribe to events which have more specific EventArgs.

Extension methods are another plus, but you already mentioned that.




回答2:


No, no good reason.

If your events do not require EventArgs or a sender object, then you don't need to use EventHandler or EventHandler<T>.




回答3:


The reason EventHandler is convention is that it supports a unified way of working with events.

The EventHandler for example always has a sender which comes out handy.

Rule of thumb here is that when you are working with WinForms and creating custom controls or extending e.g. Form, you really should use EventHandler. For your own classes: go wild.



来源:https://stackoverflow.com/questions/4828212/should-eventhandler-always-be-used-for-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!