它是安全的代表加入到与关键字新的事件? [英] Is it safe to add delegates to events with keyword new?
问题描述
有一件事我所关心的是,我发现注册代表事件的两种方式。
One thing I am concerned with is that I discovered two ways of registering delegates to events.
- OnStuff + = this.Handle;
- OnStuff + =新StuffEventHandler(this.Handle);
第一个是干净的,它是有道理的做OnStuff - = this.Handle;从事件注销...但与后者的情况下,应该怎么做OnStuff - =新StuffEventHandler(this.Handle);?这感觉就像我没有删除任何东西,因为我扔在另一个StuffEventHandler参考。是否该事件作为参考比较的委托?我很担心,我可以在这里开始讨厌的内存池。给我?我没有提及新StuffEventHandler我previously注册。
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?
What is the downside of doing #1?
什么是做#2的好处?
What is benefit of doing #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 - =新StuffEventHandler(this.Handle);去除code做的没有的比较,你通过引用删除委托:它检查是否相等比较参考目标方法(S),该委托将调用,并从删除匹配代表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本身就是一个委托对象(即我假设你已经在你的宣言事件关键字简单地限制了委托的访问)。
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).
这篇关于它是安全的代表加入到与关键字新的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!