如何在类的Dispose方法中取消订阅匿名函数?

时间:2012-03-16 22:27:03

标签: c# dispose anonymous-function unsubscribe

我有一个A类...在它的构造函数中...我正在为Object_B的eventHandler分配一个匿名函数。

如何从A类的Dispose方法中删除(取消订阅)?

任何帮助将不胜感激!感谢

Public Class A
{

public A()
 {

 B_Object.DataLoaded += (sender, e) =>
                {
                   Line 1
                   Line 2
                   Line 3
                   Line 4
                };
 }

Public override void Dispose()
{
  // How do I unsubscribe the above subscribed anonymous function ?
}
}

3 个答案:

答案 0 :(得分:7)

基本上,你不能。将其移动到方法中,或使用成员变量来保留委托以供日后使用:

public class A : IDisposable
{
    private readonly EventHandler handler;

    public A()
    {
        handler = (sender, e) =>
        {
           Line 1
           Line 2
           Line 3
           Line 4
        };

        B_Object.DataLoaded += handler;
     }

     public override void Dispose()
     {
        B_Object.DataLoaded -= handler;
     }
}

答案 1 :(得分:0)

执行此操作的正确方法是使用Rx扩展。在这里观看视频:

http://msdn.microsoft.com/en-us/data/gg577611

我发现“布鲁斯”电影特别有用。

答案 2 :(得分:0)

这是一种不使用处理程序变量的替代方法。

Public Class A
{

 public A()
  {

    B_Object.DataLoaded += (sender, e) =>
                {
                   Line 1
                   Line 2
                   Line 3
                   Line 4
                };
  }

  Public override void Dispose()
  {
   if(B_Object.DataLoaded != null)
   {
     B_Object.DataLoaded -=
         (YourDelegateType)B_Object.DataLoaded.GetInvocationList().Last();
       //if you are not sure that the last method is yours than you can keep an index
       //which is set in your ctor ...
   }
  }
 }