c# - C#取消订阅匿名方法

标签 c# delegates anonymous-methods

是否可以取消订阅事件的匿名方法?

如果我订阅这样的事件:

void MyMethod()
{
    Console.WriteLine("I did it!");
}

MyEvent += MyMethod;

我可以这样取消订阅:

MyEvent -= MyMethod;

但是如果我使用匿名方式订阅:

MyEvent += delegate(){Console.WriteLine("I did it!");};

是否可以取消订阅此匿名方法?如果是,怎么办?

最佳答案

Action myDelegate = delegate(){Console.WriteLine("I did it!");};

MyEvent += myDelegate;


// .... later

MyEvent -= myDelegate;

只保留对委托(delegate)的引用。

关于c# - C#取消订阅匿名方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/183367/

相关文章:

c# - WPF 资源字典生成操作

iphone - UIView 从 superview 中移除的速度很慢

c# - 在哪里使用事件和委托(delegate)?

c# - 如何识别 System.Reflection 中的匿名方法

c# - 像 StackoverFlow 一样设置日期时间格式

c# - 为什么 "i"被替换为 "ı"

delphi - 匿名方法转换为指针

IEnumerable<T> 的 C# 匿名方法变量范围问题

c# - URL unicode参数解码C#

c# - C# 中自定义委托(delegate)的示例用法