Avoid lots of custom EventArgs?

The class library in which I am refactoring has a large number of events (over 50), each with its own delegate, although many of them have the same arguments. I'm starting to switch them all to use EventHandler and custom EventArgs, but it turns out to be tedious and time consuming.

Is there an easier way to deal with such a situation when you have a huge number of events?

+4
source share
2 answers

You definitely don't need your own delegate type โ€” you can use EventHandler<TEventArgs> , where TEventArgs is your specific EventArgs subclass.

Refactoring a big mess is always time consuming and annoying. If you switch to using method group transformations, this may make things easier in the future:

 // This... foo.SomeEvent += new MyCustomEventHandler(SomeMethod); // becomes this.. foo.SomeEvent += SomeMethod; 

Then, if the type of SomeEvent changes, you can change SomeMethod and the subscription will work, without the need to change it again.

If you need several different subtypes of EventArgs , thatโ€™s another thing - and itโ€™s impossible to say without knowing your specific situation. If you need to convey a large amount of information, this may make sense.

+6
source

I use the templatized class of args events, as shown below, so as not to create a large number of custom event argument classes.

 public class MessageEventArgs<T> : EventArgs { public MessageEventArgs(T message) { Message = message; } public T Message { get; private set; } } 
+2
source

Source: https://habr.com/ru/post/1309491/


All Articles