从类实例的派生类中删除 (-=) Form#FormClosed 事件添加 (+=)?
我有一个派生自 System.Windows.Form.Form 的“MyForm”。 MyForm 处理 FormClosed 事件,我在构造函数中设置了该事件的处理程序。实例化的 MyForm 对象是否可以使用 -= 成功删除我的 MyClass#FormClosed 处理程序?如果重要的话,我正在使用匿名方法来连接我的 FormClosed 事件。
// In MyForm Constructor, this ALWAYS gets fired...
FormClosed += (_sender, _args) => { m_mutex.Dispose(); m_mutex = null; };
// In Instantiating Class
MyForm form = new MyForm();
form.FormClosed += (_sender, _args) => { };
// I have also tried using "delegate(object sender, EventArgs e)" and neither worked.
I have a "MyForm" that derives from System.Windows.Form.Form. MyForm handles the FormClosed event whose handler I set up in the constructor. Is it possible for an instantiated MyForm object to successfully remove my MyClass#FormClosed handler using -=? I am using an anonymous method to wire my FormClosed event if that matters.
// In MyForm Constructor, this ALWAYS gets fired...
FormClosed += (_sender, _args) => { m_mutex.Dispose(); m_mutex = null; };
// In Instantiating Class
MyForm form = new MyForm();
form.FormClosed += (_sender, _args) => { };
// I have also tried using "delegate(object sender, EventArgs e)" and neither worked.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以删除它 - 但如果您使用了匿名函数,那就有点棘手了。
基本上,您要么需要停止使用匿名函数(即将行为放入方法中),要么需要一个字段来存储匿名函数的值delegate:
就我个人而言,我倾向于将逻辑转移到方法中,除非由于某种原因它确实很棘手。
Yes, you can remove it - but if you've used an anonymous function, it's slightly trickier.
Basically you'll either need to stop using an anonymous function (i.e. put the behaviour into a method) or you'll need to have a field to store the value of the delegate:
Personally I'd favour moving the logic into a method unless it's really tricky for some reason.
是的,您可以取消订阅任何事件,甚至可以在
Dispose()
方法中取消订阅。Yes, you can unsubscribe from any of the events, even in the
Disposed()
method.