有没有办法通过传递运算符+ =和 - =作为参数来在c#中添加和删除事件处理程序,所以单个方法可以做到这一点?
我试图避免重复:
AttachHandlers()
{
event1 += handler1;
event2 += handler2;
// etc...
}
DetachHandlers()
{
event1 -= handler1;
event2 -= handler2;
// etc...
}
或
AttachDetachHandlers(bool attach)
{
if (attach)
{
event1 += handler1;
event2 += handler2;
// etc...
}
else
{
event1 -= handler1;
event2 -= handler2;
}
}
相反,我想写这样的东西:
AttachDetachHandlers(operator addRemove)
{
addRemove(event1, handler1);
addRemove(event2, handler2);
// etc...
}
使用类似的东西:
AttachDetachHandlers(+=);
理想情况下,它应该适用于事件&处理程序具有不同的签名(就像+ =& - = do)。
答案 0 :(得分:3)
你可以试试这个:
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...
}
然后像这样使用:
AttachDetachHandlers<int>(Attach);
//...
AttachDetachHandlers<int>(Detach);
答案 1 :(得分:0)
使用此示例代码。但请注意,事件处理程序的签名必须相同。
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); }
}