Home > Backend Development > C++ > How Can I Unsubscribe from Anonymous Event Handlers in C#?

How Can I Unsubscribe from Anonymous Event Handlers in C#?

Linda Hamilton
Release: 2025-01-27 07:21:10
Original
328 people have browsed it

How Can I Unsubscribe from Anonymous Event Handlers in C#?

Unsubscribing from an anonymous event handler in C#

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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template