Unsubscribe anonymous method in C#

前端 未结 11 1376
夕颜
夕颜 2020-11-22 05:16

Is it possible to unsubscribe an anonymous method from an event?

If I subscribe to an event like this:

void MyMethod()
{
    Console.WriteLine(\"I di         


        
11条回答
  •  轮回少年
    2020-11-22 05:57

    Action myDelegate = delegate(){Console.WriteLine("I did it!");};
    
    MyEvent += myDelegate;
    
    
    // .... later
    
    MyEvent -= myDelegate;
    

    Just keep a reference to the delegate around.

提交回复
热议问题