2012-03-16 56 views
5

我有一个类A ...在它的构造函数中......我将一个匿名函数分配给Object_B的eventHandler。如何在类的Dispose方法中取消订阅匿名函数?

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

什么是B_Object?它是A类的成员变量吗?它在A以外的任何地方访问;它可能有其他听众吗? – 2012-03-16 22:29:36

+0

[在C#中取消订阅匿名方法]的可能重复(http://stackoverflow.com/questions/183367/unsubscribe-anonymous-method-in-c-sharp) – 2012-03-16 22:31:19

+0

是的,它是成员... B类的哪个实例 – Relativity 2012-03-16 22:32:43

回答

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

该死的,你打败了我! – Robbie 2012-03-16 22:31:48

+0

那么,如果我们没有取消订阅......它会明显引入内存泄漏,对吧? – Relativity 2012-03-16 22:38:15

+1

@相关性:不一定。你还没有真正谈论过'B_Object.DataLoaded' - 如果这实际上是一个实例事件而不是一个静态事件,那么如果这个对象被收集,事件订阅将不再成为问题。这一切都取决于上下文... – 2012-03-16 22:40:24

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