C#.NET适当的事件订阅和取消订阅 [英] C# .NET proper event subscribing and un-subscribing

查看:61
本文介绍了C#.NET适当的事件订阅和取消订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以连续运行的应用程序,它创建和销毁类,其中一些类具有诸如鼠标单击事件之类的事件……第一个问题是退订的正确方法是什么?如果订阅看起来像这样:

I have an application that runs continuously, it creates and destroys classes some of which have events like mouse click events and the like... First question is what is the proper way to unsubscribe? If the subscribe looks like this:

Panel1.MouseClick += new MouseEventHandler(Action_MouseClick);

像这样退订是否合适:

Panel1.MouseClick -= new MouseEventHandler(Action_MouseClick);

或者可以这样做吗?

Panel1.MouseClick -= Action_MouseClick;

还是可以吗?

我的另一个问题是,如果我使用Microsoft Visual C#Studio通过设计器创建事件,它会作为处置"方法的一部分自动退订吗?还是我仍然需要在代码中放入unsubscribe方法?

My other question is is If I use the Microsoft Visual C# studio to create the events through the designer, does it automatically unsubscribe as part of the 'Dispose' method? Or do I still need to put the unsubscribe method in the code?

推荐答案

两种退订方法都具有相同的效果,而且都是正确的.

Either way of unsubscribing will have the same effect, and both are correct.

关于您的其他问题..如果您使用设计器为窗体上的控件创建事件,则在处理窗体时,事件源将不再存在,因此将不会调用它们.我想我是说没有必要分离这些事件.

As for your other question .. if you use the designer to create events for controls on a form, when the form is disposed the source of the events no longer exists, so they won't be called. I guess I'm saying it isn't necessary to detach those events.

这篇关于C#.NET适当的事件订阅和取消订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆