注销事件与委托的新实例 [英] Unregister events with new instance of the delegate
本文介绍了注销事件与委托的新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
EventHandler a = new EventHandler(control_RegionChanged);
EventHandler b = new EventHandler(control_RegionChanged);
if (a == b)
{
Console.WriteLine("Same!");
}
else
{
Console.WriteLine(a.GetHashCode() + " " + b.GetHashCode());
}
这写一样!
控制台
control.RegionChanged += new EventHandler(control_RegionChanged);
control.RegionChanged -= new EventHandler(control_RegionChanged);
这代码执行后,在事件处理程序
?未登记
After this code executes, is the EventHandler
unregistered?
推荐答案
是的;代表们在实例比较,的MethodInfo
;如果这些是相同的,那么它会工作。试图取消匿名方法时,问题就来了; 。在这种情况下,你必须坚持到委托的引用,以取消
Yes; delegates are compared on the instance and MethodInfo
; if those are the same, then it will work. The problem comes when trying to unsubscribe an anonymous method; in that case, you must keep a reference to the delegate in order to unsubscribe.
所以:
这是罚款:
control.SomeEvent += obj.SomeMethod;
//...
control.SomeEvent -= obj.SomeMethod;
但是,这是非常高风险的:
But this is much riskier:
control.SomeEvent += delegate {Trace.WriteLine("Foo");};
//...
control.SomeEvent -= delegate {Trace.WriteLine("Foo");};
匿名方法的正确方法是:
The correct process with anonymous methods is:
EventHandler handler = delegate {Trace.WriteLine("Foo");};
control.SomeEvent += handler;
//...
control.SomeEvent -= handler;
这篇关于注销事件与委托的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文