Unsubscribe anonymous method in C#

前端 未结 11 1374
夕颜
夕颜 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:51

    Since C# 7.0 local functions feature has been released, the approach suggested by J c becomes really neat.

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

    So, honestly, you do not have an anonymous function as a variable here. But I suppose the motivation to use it in your case can be applied to local functions.

提交回复
热议问题