【问题标题】:Removing anonymous event handlers [duplicate]删除匿名事件处理程序 [重复]
【发布时间】:2011-09-21 13:30:41
【问题描述】:

可能重复:
C#: How to remove a lambda event handler

是否可以删除作为匿名函数附加的事件处理程序?假设我有一个活动,我以这种方式订阅它:

TestClass classs = new TestClass ();
classs.myCustomEvent +=  (a,b) => { Console.Write(""); };

是否可以使用 -= 以某种方式删除此事件处理程序?

【问题讨论】:

    标签: c# events event-handling


    【解决方案1】:

    可以,但是需要先存到局部变量中:

    MyDelegate handler = (a, b) => { Console.Write(""); };
    class.myCustomEvent += handler;
    class.myCustomEvent -= handler;
    

    【讨论】:

    • 不知道为什么这被否决了... +1,这是一个正确的答案。除了关于“本地”变量的部分:在大多数情况下,您需要将其存储在更长寿的位置...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 2010-11-24
    • 2016-07-05
    • 2012-05-10
    • 2010-11-21
    相关资源
    最近更新 更多