.NET Event Best Practice - Expose via property or return in EventArgs [closed]
开发者_JS百科
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this questionI'm unsure about the best practice for event handling/class design.
I have a class that has a method Discover. When the method completes it raises an event, DiscoveryCompleted. The DiscoveryCompleted event has EventArgs.
In the Discover method a List of objects are created. Should these be returned when the DiscoveryCompleted event fires in the EventArgs (will still need to create a class that derives from EventArgs), or be set as a property (ReadOnlyCollection) on the class. I have a bool Discovered which is set when the DiscoveryCompleted fires, so this can be used to determine if data should be populated.
If the data is either transitive (where the value might change after the event has fired and you want subscribers to be able to view the data that pertains to that particular event) or not directly related to your component (the result of an async call that the component won't use itself later), then return it in the event args.
Otherwise, if it would make sense to expose the value as a property on the component (disregarding your event), then do that and don't worry about the EventArgs
. If not, then include it in the args.
I think most developers would return them in a class that inherits from EventArgs. This way any method subscribing to your event would have the result right there in their event handler.
class EventArgsX : EventArgs {
public IEnumerable<object> YourCollection { get; set; }
}
instance.SomeEvent += (s, args) => {
foreach(object O in args.YourCollection){
//do something
}
}
A lot is left out, but I'm sure you get the point.
It depends on the nature of the data in question. If it makes sense for the data to be part of the class, then there should be a property for it. If it doesn't make sense for the class to encapsulate the data, then create an EventArg class for it.
Think about how Control events are done. CheckBox.CheckChanged doesn't pass the Checked state because that makes sense as a property for the CheckBox class, but the KeyPress event passes KeyPressEventArgs because the key that was pressed has nothing to do with the CheckBox itself.
I think this ultimately boils down to the architecture / extensibility points you want to enable with your code. Does a consumer of the Discover
function always want to / need to interact with the object
s that are discovered? If so then they should be returned from the Discover
method. However, if calling Discover
keeps those objects for use internally with other methods, and knowing which objects were discovered were optional (or you don't want to do something with them beyond the classes core functionality every time), then providing the information through an event is a good choice.
精彩评论