我写了一些课:
public class A
{
public A()
{
serviceAdapter.CompletedCallBackEvent += new EventHandler( foo );
.
.
.
}
void foo(object sender, EventArgs e)
{
serviceAdapter.CompletedCallBackEvent -= new EventHandler( foo );
}
}
现在,我想用匿名方法更改此回调侦听器 - 但我不知道如何在匿名方法中删除回调侦听器。
class A
{
public A()
{
serviceAdapter.CompletedCallBackEvent += delegate( object sender, EventArgs ee )
{
... need to remove the listener to the event.
}
}
}
答案 0 :(得分:4)
您可以简单地将您的委托/处理程序分配给私有变量。
private EventHander _handler = null;
public A()
{
_handler = delegate( object sender, EventArgs ee)
{
ServiceAdapter.CompletedCallBackEvent -= _handler;
};
ServiceAdapter.CompletedCallBackEvent += _handler;
}
答案 1 :(得分:4)
您无法删除此类匿名委托。请参阅有关匿名代表的MSDN文章。另外值得一读this article
您可以这样做:
public A()
{
EventHandler myHandler = null;
myHandler = new EventHandler(delegate(object s, EventArgs e)
{
serviceAdapter.CompletedCallbackEvent -= myHandler;
});
serviceAdapter.CompletedCallBackEvent += myHandler;
}