Should I use EventArgs or a simple data type?

2019-06-20 04:38发布

I'm currently creating a library for fun and practice and I was wondering, when raising an event, how to choose between passing your own EventArgs derivative or just the data type.

For example, in my library I have something like this:

public delegate void LostConnectionEventHandler(string address);
public delegate void MessageReceieved(byte[] bytes);

What is the standard practice for this? Should I replace string address with ConnectionEventArgs and byte[] bytes with MessageEventArgs?

I know either one works just fine and this question may be subjective but I am still curious on the thought process higher-level programmers go through when deciding whether or not to include their own EventArgs or just to pass the data in directly.

Thanks!

5条回答
Luminary・发光体
2楼-- · 2019-06-20 04:54

The .NET Framework guidelines indicate that the delegate type used for an event should take two parameters, an "object source" parameter indicating the source of the event, and an "e" parameter that encapsulates any additional information about the event. The type of the "e" parameter should derive from the EventArgs class. For events that do not use any additional information, the .NET Framework has already defined an appropriate delegate type: EventHandler.

Reference: http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx

Another useful information: http://msdn.microsoft.com/en-us/library/ms229011.aspx

查看更多
神经病院院长
3楼-- · 2019-06-20 04:56

Personally I like the idea of deriving from EventArgs,

if you have to pass status information and aggregate objects you could easily do it, see the

MouseEventArgs type for example.

using OOP approach, if you have an event/construct which accepts an object of type EventArgs you can rely on the fact that every object derived from it will work in the same way while if you have another kind of object which does not share the same base class, you could eventually break something.

hard to prove and reproduce but possible depending on the design, because events are special delegates designed to work with EventArgs and its descendants

查看更多
贼婆χ
4楼-- · 2019-06-20 05:04

In a larger project, having an EventArgs class, helps with minimizing the code you have to modify, when your event needs additional data in some cases. I usually prefere the EventArgs way instead of a direct value.

查看更多
Summer. ? 凉城
5楼-- · 2019-06-20 05:05

Within my projects I use EventArgs when the number of parameters is larger than one! Look at the NotifyPropertyChanged Event, it has one argument, which isn't an EventArgs type.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-06-20 05:20

There's no need to derive from EventArgs however the convention follows the common (Introduce Parameter Object) refactoring rule. And the rationale for this rule is well documented.

查看更多
登录 后发表回答