C# 删除事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1307607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing event handlers
提问by Carlo
Is this:
这是:
Button.Click -= new EventHandler(Button_Click);
the same as this:
与此相同:
Button.Click -= Button_Click;
I ask because to me it seems that the former is removing a new reference to a method, and the latter one is removing a method itself. But then again, maybe the new EventHandler part is implicit in the += or -= overload in case the programmer doesn't explicitly assign it like that?
我问是因为对我来说,前者似乎正在删除对方法的新引用,而后者正在删除方法本身。但话说回来,也许新的 EventHandler 部分隐含在 += 或 -= 重载中,以防程序员没有像那样显式分配它?
In case it is different how about
万一不同呢
Button.Click -= new EventHandler(Button_Click);
VS
VS
Button.Click -= Button_Click;
Thanks.
谢谢。
采纳答案by Konrad Rudolph
It is the same. The second is merely syntactic sugar for the first, and equality comparison is overloaded appropriately for delegate types:
这是相同的。第二个只是第一个的语法糖,并且对于委托类型适当地重载了相等比较:
Two delegates of the same type with the same targets, methods, and invocation lists are considered equal.
具有相同目标、方法和调用列表的相同类型的两个委托被认为是相等的。
Source: MSDN, Delegate.Equality Operator
回答by Brian Gideon
The end result is the same. The compiler is inferring the type of delegate automatically and as a result the new operator is not required to create it.
最终结果是一样的。编译器会自动推断委托的类型,因此不需要 new 运算符来创建它。