从类实例的派生类中删除 (-=) Form#FormClosed 事件添加 (+=)?

发布于 2024-11-19 10:21:25 字数 530 浏览 4 评论 0原文

我有一个派生自 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉梦枕江山 2024-11-26 10:21:25

是的,您可以删除它 - 但如果您使用了匿名函数,那就有点棘手了。

基本上,您要么需要停止使用匿名函数(即将行为放入方法中),要么需要一个字段来存储匿名函数的值delegate:

private EventHandler formClosedHandler;
...

// In constructor
formClosedHandler = (sender, args) => { ... };
FormClosed += formClosedHandler;

// Later...
FormClosed -= formClosedHandler;
formClosedHandler = null;

就我个人而言,我倾向于将逻辑转移到方法中,除非由于某种原因它确实很棘手。

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:

private EventHandler formClosedHandler;
...

// In constructor
formClosedHandler = (sender, args) => { ... };
FormClosed += formClosedHandler;

// Later...
FormClosed -= formClosedHandler;
formClosedHandler = null;

Personally I'd favour moving the logic into a method unless it's really tricky for some reason.

英雄似剑 2024-11-26 10:21:25

是的,您可以取消订阅任何事件,甚至可以在 Dispose() 方法中取消订阅。

Yes, you can unsubscribe from any of the events, even in the Disposed() method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文