.NET EventHandlers - Generic or no?

后端 未结 9 1878
遇见更好的自我
遇见更好的自我 2020-12-03 13:53

Every time I start in deep in a C# project, I end up with lots of events that really just need to pass a single item. I stick with the EventHandler/Event

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 14:20

    Delegate of the following form has been added since .NET Framework 2.0

    public delegate void EventHandler(object sender, TArgs args) where TArgs : EventArgs
    

    You approach goes a bit further, since you provide out-of-the-box implementation for EventArgs with single data item, but it lacks several properties of the original idea:

    1. You cannot add more properties to the event data without changing dependent code. You will have to change the delegate signature to provide more data to the event subscriber.
    2. Your data object is generic, but it is also "anonymous", and while reading the code you will have to decipher the "Item" property from usages. It should be named according to the data it provides.
    3. Using generics this way you can't make parallel hierarchy of EventArgs, when you have hierarchy of underlying (item) types. E.g. EventArgs is not base type for EventArgs, even if BaseType is base for DerivedType.

    So, I think it is better to use generic EventHandler, but still have custom EventArgs classes, organized according to the requirements of the data model. With Visual Studio and extensions like ReSharper, it is only a matter of few commands to create new class like that.

提交回复
热议问题