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



我在它的构造函数中有一个class a。。。我正在为Object_B的事件处理程序分配一个匿名函数。

如何从类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 ?
}
}

基本上你做不到。要么将其移动到一个方法中,要么使用成员变量保留委托以备以后使用:

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

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

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

正确的方法是使用Rx扩展。点击此处观看视频:

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

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

最新更新