问题
When we want to pass data to an event subscriber, we use EventArgs (or CustomEventArgs) for this.
.Net provides a build in type EventHandler that uses as a parameter an instance of EventArgs class that is build in as well.
What about cases, when I need to notify a subscriber that some action is over, for example search is over? I don't want to even use EventArgs, that won't contain anything.
Is there a build in type for signaling another class, without the need to use empty EventArgs?
回答1:
You can do a couple of things:
- Use your normal event with EventHandler and the basic EventArg class - sure it's empty but does this hurt?
- Make your own delegate and use this with
event MyDelegateWithoutParams MyEvent;
- Use the Observer-Pattern with IObservable instead
- Let the clients pass a Action do you and call this action
I hope one of this options is to your liking. I use 1 and 4 for this kind of situation (4 mostly if there will be only one "listener".
PS: I guess 2 won't conform to the .net framework guidelines so maybe this is not the best idea ;)
回答2:
I really would advise you to use the standard EventHandler patter here and just pass EventArgs.Empty
; however, you can use Action
as an event type of you really want - it is just unusual.
回答3:
if you use plain delegates
surely you can do what you want but if you use events
I think the best is to stick on the standard and always have object
sender and EventArgs
e.
if you really do not what to pass on firing those events from your own code, just pass EventArgs.Empty
as second parameter.
回答4:
Use Actions (below answer copied from https://stackoverflow.com/a/1689341/1288473):
Declaring:
public event Action EventWithoutParams;
public event Action<int> EventWithIntParam;
Calling:
if (EventWithoutParams != null) EventWithoutParams();
if (EventWithoutParams != null) EventWithIntParam(123);
来源:https://stackoverflow.com/questions/7455357/eventhandler-type-with-no-event-args