在C#中用Lambdas解决事件 [英] UnHooking Events with Lambdas in C#
问题描述
我经常碰到一个我想订阅一个事件的情况,但是我想使用一个lambda来实现:
I often run into a situation where I want to subscribe to an event, but I want to use a lambda to do so:
public class Observable
{
public event EventHandler SomethingHappened;
public void DoSomething()
{
// Do Something...
OnSomethingHappened();
}
}
// Somewhere else, I hook the event
observable.SomethingHappened += (sender, args) => Console.WriteLine("Something Happened");
我遇到的问题是我不知道如何解除事件。由于lambda在引擎盖下创建了一个匿名委托,所以我没有什么可以调用 - =
。
The problem I run into is that I don't know how to unhook the event. Since the lambda creates an anonymous delegate under the hood, I have nothing to call -=
on.
我可以创建一个方法:
private void SomethingHappened(object sender, EventArgs args)
{
Console.WriteLine("Something Happened");
}
然后我可以挂钩/取消挂钩我想要的:
And then I can hook/unhook all I want:
observable.SomethingHappened += SomethingHappened;
observable.SomethingHappened -= SomethingHappened;
但我真的很想使用我的lambda。在一个更复杂的例子中,羊羔在这里非常方便。
But I'd really, really, really like to use my lambda instead. In a more complicated example, lambdas come in really handy here.
我很确定我没有运气,但我想知道有没有人想出了这样做?
I am pretty sure that I am out of luck... but I was wondering if anyone out there has figured out a way to do this?
推荐答案
不用说,没有一个很好的方式来做到这一点。
Unforutantely there is not a great way to do this. You are really stuck with one of two options
- 使用您所描述的方法
- 分配lambda到变量,并使用该变量来添加/删除事件
这篇关于在C#中用Lambdas解决事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!