处置后我需要删除控件吗?
.NET 2
// dynamic textbox adding
myTextBox = new TextBox();
this.Controls.Add(myTextBox);
// ... some code, finally
// dynamic textbox removing
myTextBox.Dispose();
// this.Controls.Remove(myTextBox); ?? is this needed
小解释
- 当然,如果我处置一个控件,我将不再看到它,但无论如何,它会在父控件集合中保留为“Nothing”吗?
- 我还需要像 MSDN 建议的那样,从控件中删除所有处理程序吗?
.NET 2
// dynamic textbox adding
myTextBox = new TextBox();
this.Controls.Add(myTextBox);
// ... some code, finally
// dynamic textbox removing
myTextBox.Dispose();
// this.Controls.Remove(myTextBox); ?? is this needed
Little explanation
- Surely, if I Dispose a control I will not see it anymore, but anyway, will remain a "Nothing" in the parent controls collection?
- need I also, like MSDN recommends, remove all handlers from the control?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不,你不知道。
我试过了。
您可以将以下代码粘贴到LINQPad中:
编辑:控件将 从表单的
Controls
集合中删除。为了演示这一点,请将点击处理程序替换为以下内容:它将显示
0
。第二nd编辑:
Control.Dispose(bool diswriting)
包含以下代码:No, you don't.
I tried it.
You can paste the following code into LINQPad:
EDIT: The control will be removed from the form's
Controls
collection. To demonstrate this, replace the click handler with the following:It will show
0
.2nd EDIT:
Control.Dispose(bool disposing)
contains the following code:编辑:
MSDN 建议您从控件中删除对象,然后在运行时从集合中删除对象时调用 dispose:
http://msdn.microsoft.com/en-us/library/82785s1h%28VS.80%29.aspx
EDIT:
MSDN suggests that you remove the object from the Control and then call dispose when removing an object from a collection at runtime:
http://msdn.microsoft.com/en-us/library/82785s1h%28VS.80%29.aspx
但从 Mat 的答案来看,这种行为似乎取决于所使用的框架。我认为他建议在使用紧凑框架时必须删除并处置一些控件。
因此,微软建议我们总是删除然后处置,这是有道理的,特别是当您将代码模块移动到其他框架时。
MRP
But looking at the answer from Mat it looks as though this behavior depends on the framework being used. I think he's suggesting that when using the compact framework some controls must be Removed and also Disposed.
So Microsoft suggesting that we always remove and then dispose kind of makes sense especially if you're moving code modules to other frameworks.
MRP
经过一些测试,我发现已处理的控件会自动从父控件集合中删除。
更新:
从控件的 Dispose(bool) 方法
After some tests, I find out that the disposed controls are automatically removed from the parent control collection.
UPDATE
from the control's Dispose(bool) method:
有关 Compact Framework 2 + VS2005 的更多信息
如果设计器未实现以下功能,则在删除派生自 swfcontrol 的控件时,设计器可能会崩溃:
Further Information on Compact Framework 2 + VS2005
Designer may crash when removing a control which is derived from s.w.f.control, if it doesn't implement the following:
请记住,如果您有一些代码来迭代控件并执行某些操作,那么如果这些控件之一已被释放,您将收到异常。因此,一般来说,我可能会建议删除该控件作为良好实践。
Just keep in mind that if you have some code to iterate over your controls and do something, you would get an exception if one of these controls had been disposed. Therefore, in general I would probably recommend removing the control as good practice.