如果我创建这样的lambda回调:
var someInstance = new SomeObject();
someInstance.Finished += (obj, args) =>
{
// Do something
// Deregister here
};
someInstance.DoAction();
我如何注销回调作为实际处理程序代码的一部分?这种模式非常理想,因为我可以确保尽快发布它。
我见过类似的问题,但是没有一个问题可以直接解决这种类型的示例。
最佳答案
您可以在lambda中使用MethodInfo.GetCurrentMethod
来检索lambda的MethodInfo。
使用MethodInfo,您可以使用Delegate.CreateDelegate
获取代表您的lambda的正确类型的委托(delegate)。
使用委托(delegate),您可以注销lambda,而无需将函数存储在变量中或将其命名为方法。
class MyClass
{
public event EventHandler TheEvent;
void TestIt()
{
TheEvent += (sender, eventargs) =>
{
Console.WriteLine("Handled!"); // do something in the handler
// get a delegate representing this anonymous function we are in
var fn = (EventHandler)Delegate.CreateDelegate(
typeof(EventHandler), sender,
(MethodInfo)MethodInfo.GetCurrentMethod());
// unregister this lambda when it is run
TheEvent -= fn;
};
// first time around this will output a line to the console
TheEvent(this, EventArgs.Empty);
// second time around there are no handlers attached and it will throw a NullReferenceException
TheEvent(this, EventArgs.Empty);
}
}
关于c# - 如何注销Lambda回调?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5797330/