When handling events in C#, subscribing to events using named methods allows easy unsubscription using the -= operator. But what if you use anonymous methods? Is it possible to unsubscribe from them?
The answer is yes. Do not subscribe directly using the anonymous method, instead assign it to the Action proxy variable. By maintaining a reference to the agent, you can later remove the handler using the -= operator.
<code class="language-c#">Action myDelegate = delegate() { Console.WriteLine("I did it!"); }; MyEvent += myDelegate; // .... later MyEvent -= myDelegate;</code>
The above is the detailed content of How Can I Unsubscribe from Anonymous Event Handlers in C#?. For more information, please follow other related articles on the PHP Chinese website!