如何注销匿名处理程序?
C# 2.0 有一个巧妙的功能,称为匿名函数。 这主要用于事件:
Button.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };
现在,假设 Button 是静态成员,然后向其添加委托将被视为非托管资源。 通常,我必须先取消注册该处理程序,然后才能再次对其进行重新字符串化。 这是 GUI 编程的一个非常常见的用例。
匿名函数的指导原则是什么? 框架会自动取消注册吗? 如果是的话,什么时候?
C# 2.0 has a neat feature called anonymous functions. This is intended to be used mostly with events:
Button.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };
Now, suppose that Button is a static member, then adding delegates to it would count as unmanaged resources. Normally, I would have to deregister the handler before regestring it again. This is a pretty common use case for GUI programming.
What are the guidelines with anonymous functions? Does the framework deregrister it automatically? If so, when?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,匿名函数不会自动取消注册。 如果不应在应用程序的整个生命周期中连接该事件,您应该确保自己执行此操作。
当然,要做到这一点,您必须存储委托引用,以便能够取消注册它。
类似于:
另外,请参阅此问题。
No, anonymous functions will not get deregistered automatically. You should make sure to do it yourself, if the event should not be hooked up for the whole lifetime of your application.
To do this, of course, you would have to store the delegate reference, to be able to de-register it.
Something like:
Also, see this question.
如果我没记错的话(并且我记得我在哪里读到过这篇文章)内联匿名委托不能被删除。
您需要分配给(静态)委托字段。
If I recall correctly (and I can recall where I read this) inline anonymous delegates cannot be removed.
You would need to assign to a (static) delegate field.