How to unsubscribe an anonymous function in Dispose method of a class?

六月ゝ 毕业季﹏ 提交于 2019-12-10 14:22:11

问题


I have a Class A...in it's constructor...I am assigning an anonymous function to Object_B's eventHandler.

How do I remove (unsubscribe) that from Dispose method of class A ?

Any help would be appreciated ! Thanks

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

回答1:


You can't, basically. Either move it into a method, or use a member variable to keep the delegate for later:

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



回答2:


The right way to do this is to use the Rx Extensions. Go watch the videos here:

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

I found the "blues" movie particularly useful.




回答3:


This is an alternative without using a handler variable.

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


来源:https://stackoverflow.com/questions/9745280/how-to-unsubscribe-an-anonymous-function-in-dispose-method-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!