2012-03-16 26 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 ... 
    } 
    } 
}