I have a MulticastDelegate
that can reference one of a number of (legacy) delegates that have the same signature. For example:
public delegate void ObjectCreated(object sender, EventArgs args);
public delegate void ObjectDeleted(object sender, EventArgs args);
//...
Those delegates are then used to define events:
public event ObjectCreated ObjectWasCreated;
public event ObjectDeleted ObjectWasDeleted;
I then have a method which takes in a MulticastDelegate
that I use to do some common checking:
void DispatchEvent(MulticastDelegate handler, object sender, EventArgs args)
{
if (handler != null)
{
// ...
handler.DynamicInvoke(sender, args);
}
}
Which is called from within other methods of the class wherein the events were defined:
DispatchEvent(ObjectWasCreated, sender, args);
DispatchEvent(ObjectWasDeleted, sender, args);
Is there a more concise way to do this that avoids DynamicInvoke?
You could do something like:
I'm not sure if this'll be faster than using DynamicInvoke, though.
You'll have to use reflection somewhere. If each delegate could be guarenteed to only have one subscriber, then you could use the Delegate.Method property directly when creating the
EventHandler
, but as they're events, they're likely to have more than one subscriber...Here's my reflection-free solution. It basically implements a multicast delegate as a list. Less code? No. Better performance? I don't know. Cleaner? Meh.
One simple alternative is to use built in types like
Action<,>
orEventHandler
instead of custom delegates, so that you get strong types.or
Now your method call will be straightforward.
But that's mostly not a good solution.
You could use
dynamic
, still much better thanDynamicInvoke
:Or may be generics:
I did a small performance comparison and found
dynamic
to be too good actually: