简体   繁体   中英

EventHandler vs. EventHandler<TEventArgs>

According to the accepted answer here there is no difference, but in MSDN :

Typically, you do not have to declare a delegate for an event, because you can use either the EventHandler or the EventHandler<TEventArgs> delegate. You should declare a delegate only in rare scenarios, such as making your class available to legacy code that cannot use generics.

So it seems to me that Microsoft highly recommend the generic approach over the simplified and less typing one, but I cannot figure out why or what is the difference?

I believe both the accepted answer and the MSDN documentation you link to state the same thing, to use either EventHandler or EventHandler<"T"> (the less typing one) instead of creating your own custom delegates.

From the accepted answer: "...you should probably prefer the former over the latter because it's clearer and requires less typing."
The former being:

public event EventHandler<MyEventArgs> SomeEvent;

And from MSDN: For scenarios where the EventHandler and EventHandler<"TEventArgs"> delegates do not work, you can define a delegate.
Defining a delegate is the 'latter' from the accepted answer:

public delegate void MyEventHandler(object sender, MyEventArgs e);

In my opinion, as soon as EventHandler<MyEventArgs> occurs at least twice in your project, you have produced hard-to-maintain copy & paste code:

public event EventHandler<MyEventArgs> ItemBeginningEdit;                ^
public event EventHandler<MyEventArgs> ItemCommited;                     |
public event EventHandler<MyEventArgs> ItemEditCancelled;                |
...

In order to keep your code clean, you should abstract the event handler type by defining your own MyEventHandler delegate in this case. If you later want to switch from let's say MyEventArgs to MyEventArgs2 , you only have to change it in one single place:

public delegate void MyEventHandler(object sender, MyEventArgs2 e);
public event MyEventHandler ItemBeginningEdit;                ^
public event MyEventHandler ItemCommited;                     |
public event MyEventHandler ItemEditCancelled;                |
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM