2011-06-06 58 views
4

我写了一些类:如何去除匿名方法的回调监听?

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. 
      } 
    } 
} 

回答

4

您可以简单地将您的委托/处理程序分配给一个私有变量。

private EventHander _handler = null; 

public A() 
{   
    _handler = delegate(object sender, EventArgs ee) 
     {   
      ServiceAdapter.CompletedCallBackEvent -= _handler; 
     }; 
    ServiceAdapter.CompletedCallBackEvent += _handler; 
} 
+0

你怎么可以指定委托私有变量?我试着和它不工作(不编译) – Yanshof 2011-06-06 13:32:43

+0

@Yanshof:你可以在你的EventHandler类中创建一个私有变量,而不是我上面提到的CompletedCallBackEventHandler(它是一种伪代码)......你能不能提一下哪种类型的错误你越来越?我假设这是“CompletedCallBackEventHandler”上的错误你也在你的方法/构造函数中分配这个私有变量 – Hasanain 2011-06-06 13:37:31

+0

我是这样写的 - 它不是编译 – Yanshof 2011-06-06 13:41:09

4

您不能删除这样的匿名委托。有关匿名代表的信息,请参见MSDN。另外值得一读this article

您可能能够做到:

 public A() 
    { 
     EventHandler myHandler = null; 
     myHandler = new EventHandler(delegate(object s, EventArgs e) 
      { 
       serviceAdapter.CompletedCallbackEvent -= myHandler; 
      }); 

     serviceAdapter.CompletedCallBackEvent += myHandler; 
    } 
+0

我把'myEvent'修正为'serviceAdapter.CompletedCallbackEvent',这样可以+1。 – user7116 2011-06-06 13:53:59

+0

@sixlettervariables谢谢,我错过了。 – IndigoDelta 2011-06-06 14:11:07

+0

没问题,先生,看起来像复制/粘贴省略。 – user7116 2011-06-06 14:13:50