Creating custom events - Object Sender or Typed Sender?

风格不统一 提交于 2019-12-04 03:53:52

I actually am quite confused why, when designing the .Net Framework v2, MS didn't provide an EventHandler just the way you described - with the TSender and TEventArgs as both generic arguments. (In v1 and v1.1, since they didn't have generics, I completely understand why they didn't make thousands of extra delegate types to handle all the possible events.) If I remember properly, you can still use a generalized handler to listen to a more specific event:

public event EventHandler<Button, MouseDownEventArgs> MouseDown;

private void ObservingMethod(object sender, EventArgs e) { }

MouseDown += new EventHandler<Button, MouseDownEventArgs>(ObservingMethod);

Since you're not exposing the observer to the observable, I don't see how this could be a problem; you're just preventing the need to do type-checking 'just in case' once you get to the event handler. I think it'd be a fantastic practice, although a bit non-standard since MS decided not to include it.

As noted in my comment above, I would prefer to see the following definition of EventHandler, so that you really could always use a very generalized handler method, as my code sample:

public delegate void EventHandler<TSender, TEventArgs>(TSender sender, TEventArgs e)
    where TEventArgs : EventArgs;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!