Should I use EventArgs or a simple data type?

2019-06-20 05:00发布

问题:

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!

回答1:

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



回答2:

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



回答3:

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.



回答4:

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.



回答5:

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.