为什么是“新的”操作员使用 - =?分离事件处理程序? [英] Why is "new" operator working for detaching a eventhandler using -=?
问题描述
为什么我必须使用以下内容来分离事件?
object.myEvent - = new MyEvent(EventHandler) ;
我对于新操作符的工作感到非常恼火。 p>
可以解释一下吗?
更新
我已经知道,我不必使用新的操作符来分离事件,但它仍然是Visual Studio 2010中的自动完成建议。我真正的问题是 - =新的工作为分离处理。新的对象/委托如何与先前创建的对象/代理匹配在+ =侧?
您没有使用新的
运算符。你没有必要,因为C#2.0出来了:
foo.SomeEvent + = EventHandler;
foo.SomeEvent - = EventHandler;
这使用方法组转换从方法组中创建一个委托(方法的名称)。这不仅仅是为了事件:
Action< string> writeToConsole = Console.WriteLine;
编辑:至于如何有效:
- 在事件上使用
- =
最终会调用删除访问器,通常使用- =
代表...(至少有效) - 使用
- =
代表是代理的语法糖。删除
-
Delegate.Remove
使用委托相等 - 两个委托实例相等它们具有相同的方法和相同的目标实例(例如方法)
请注意,使用方法组转换仍将创建一个新的代理人的每个代码实例。
Why do I have to use the following to detach an event?
object.myEvent -= new MyEvent(EventHandler);
I am some how irritated that the new operator is working.
Can some one explain?
Update
I already know that i don't have to use the new operator for detaching events, but it is still the auto complete suggestion in Visual Studio 2010. My real question is how does -= new work for the detach process. How can a new object / delegate match a prior created object / delegate on the += side?
You don't have to use the new
operator. You haven't had to since C# 2.0 came out:
foo.SomeEvent += EventHandler;
foo.SomeEvent -= EventHandler;
This uses a method group conversion to create a delegate from the method group (the name of the method). This isn't just for events, either:
Action<string> writeToConsole = Console.WriteLine;
EDIT: As for how it works:
- Using
-=
on an event just ends up calling the "remove" accessor, which typically uses-=
on a delegate... (at least effectively) - Using
-=
on a delegate is syntactic sugar forDelegate.Remove
Delegate.Remove
uses delegate equality - two delegate instances are equal if they have the same method and the same target instance (for instance methods)
Note that using a method group conversion will still create a new instance of the delegate each time you go through the code.
这篇关于为什么是“新的”操作员使用 - =?分离事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!