Reputation: 5241
Is there a way to add and remove event handlers in c# by passing the operators += and -= as arguments, so a single method could do it?
I am trying to avoid the repetitive:
AttachHandlers()
{
event1 += handler1;
event2 += handler2;
// etc...
}
DetachHandlers()
{
event1 -= handler1;
event2 -= handler2;
// etc...
}
or
AttachDetachHandlers(bool attach)
{
if (attach)
{
event1 += handler1;
event2 += handler2;
// etc...
}
else
{
event1 -= handler1;
event2 -= handler2;
}
}
Instead, I would like to write something like this:
AttachDetachHandlers(operator addRemove)
{
addRemove(event1, handler1);
addRemove(event2, handler2);
// etc...
}
being used with something like:
AttachDetachHandlers(+=);
Ideally it should work with event & handlers having different signatures (just like += & -= do).
Upvotes: 0
Views: 1260
Reputation: 1276
Use this sample code. But notice that the signature of event handlers must be the same.
class Program
{
delegate void dlgHandlerOperation<T>(ref EventHandler<T> Event, EventHandler<T> Handler);
static void SetHandler<T>(ref EventHandler<T> Event, EventHandler<T> Handler) { Event += Handler; }
static void UnsetHandler<T>(ref EventHandler<T> Event, EventHandler<T> Handler) { Event -= Handler; }
static void SetAll(dlgHandlerOperation<int> Op)
{
Op(ref ev, foo);
Op(ref ev, bar);
}
static event EventHandler<int> ev;
static void Main(string[] args)
{
SetAll(SetHandler);
ev?.Invoke(null, 5);
SetAll(UnsetHandler);
ev?.Invoke(null, 6);
}
static void foo(object sender, int e) { Console.WriteLine("foo => " + e); }
static void bar(object sender, int e) { Console.WriteLine("bar => " + e); }
}
Upvotes: 0
Reputation: 7526
You can try this:
public static void Attach<T>(ref EventHandler<T> a, EventHandler<T> b)
{
a += b;
}
public static void Detach<T>(ref EventHandler<T> a, EventHandler<T> b)
{
a -= b;
}
public static void AttachDetachHandlers<T>(Action<ref EventHandler<T>, EventHandler<T>> op)
{
op(ref event1, handler1);
op(ref event2, handler2);
//etc...
}
Then use like this:
AttachDetachHandlers<int>(Attach);
//...
AttachDetachHandlers<int>(Detach);
Upvotes: 3