Unsubscribe anonymous method in C#

前端 未结 11 1245
夕颜
夕颜 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 06:05

    One technique is to declare a variable to hold the anonymous method which would then be available inside the anonymous method itself. This worked for me because the desired behavior was to unsubscribe after the event was handled.

    Example:

    MyEventHandler foo = null;
    foo = delegate(object s, MyEventArgs ev)
        {
            Console.WriteLine("I did it!");
            MyEvent -= foo;
        };
    MyEvent += foo;
    

提交回复
热议问题