问题描述
我担心的一件事是我发现了两种注册事件代表的方法.
One thing I am concerned with is that I discovered two ways of registering delegates to events.
- OnStuff += this.Handle;
- OnStuff += new StuffEventHandler(this.Handle);
第一个是干净的,执行OnStuff -= this.Handle;"是有意义的从事件中注销...但是对于后一种情况,我应该执行OnStuff -= new StuffEventHandler(this.Handle);"吗?感觉就像我根本没有删除任何东西,因为我正在抛出另一个 StuffEventHandler 参考.事件是否通过引用比较委托?我担心我会在这里启动一个令人讨厌的内存池.找我?我没有对我之前注册的新 StuffEventHandler"的引用.
The first one is clean, and it makes sense doing "OnStuff -= this.Handle;" to unregister from the event... But with the latter case, should I do "OnStuff -= new StuffEventHandler(this.Handle);"? It feels like I am not removing anything at all, since I'm throwing in another StuffEventHandler reference. Does the event compare the delegate by reference? I am concerned I could start a nasty memory pool here. Get me? I don't have the reference to the "new StuffEventHandler" I previously registered.
做#1的缺点是什么?
做#2有什么好处?
推荐答案
你不必担心保留对最初注册的委托的引用,也不会启动一个讨厌的内存池".
You don't need to worry about keeping a reference to the originally registered delegate, and you will not start a "nasty memory pool".
当您调用OnStuff -= new StuffEventHandler(this.Handle);"时删除代码不比较您通过引用删除的委托:它通过比较对委托将调用的目标方法的引用来检查是否相等,并从OnStuff"中删除匹配的委托.
When you call "OnStuff -= new StuffEventHandler(this.Handle);" the removal code does not compare the delegate you are removing by reference: it checks for equality by comparing references to the target method(s) that the delegate will call, and removes the matching delegates from "OnStuff".
顺便说一句,OnStuff"本身就是一个委托对象(我假设您在声明中使用的 event 关键字只是限制了委托的可访问性).
By the way, "OnStuff" itself is a delegate object (the event keyword that I assume you have in your declaration simply restricts the accessibility of the delegate).
这篇关于使用关键字 new 将委托添加到事件中是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!