退出表单之前,我是否需要处理动态创建的控件? [英] Do I need to dispose of dynamically-created controls before exiting a form?

查看:90
本文介绍了退出表单之前,我是否需要处理动态创建的控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用using指令创建了选项表单的新实例,因此在完成后会自动将其丢弃.我是否需要在关闭窗体之前处理在窗体上动态创建的控件,还是在我调用this.Close()时将其自动删除?

I've created a new instance of my options form with the using directive, so it is disposed of automatically when I'm finished with it. Do I need to dispose of the dynamically-created controls on the form before closing it, or will they be automatically disposed of when I call this.Close()?

推荐答案

通常不,所有控件都是动态创建的.通常在InitializeComponent()方法中,当代码出现在其他位置时,它并没有本质上的不同.动态地删除控件会使您陷入麻烦.

Generally no, all controls are dynamically created. Usually in the InitializeComponent() method, it isn't fundamentally different when the code appears somewhere else. Dynamically removing controls is what can get you into trouble.

在处置控件的父级时,控件也将自动处置.因此,只要您通过其Collection属性将它们添加到其父项中,就不需要额外的代码来处理.触发器正在关闭使用Show()方法显示的表单的窗口,对于使用ShowDialog()显示的表单,代码中的 using 语句关闭了该窗口.

Controls are automatically disposed when their Parent is disposed. So as long as you have them added to their parent through its Collection property then you don't need extra code to dispose. The trigger is closing the window for a form that's displayed with the Show() method, the using statement in your code for a form that's displayed with ShowDialog().

您可以使用任务管理器检查是否正确.在视图+选择列"中添加USER Objects列(在Windows 8中,右键单击列表视图标题).计数器非常可靠.反复创建和关闭表单不能一直增加显示的值.

You can check that you got it right by using Task Manager. Add the USER Objects column with View + Select Columns (right-click the listview header in Windows 8). The counter is very reliable. Repeatedly creating and closing your form must not constantly increase the displayed value.

泄漏用户对象是Winforms中非常常见的错误,垃圾收集器不会使您摆脱麻烦.始终非常警惕代码中的任何ControlCollection.Clear()或Remove/At()语句.

Leaking USER Objects is a very common bug in Winforms, the garbage collector does not keep you out of trouble. Always be very wary of any ControlCollection.Clear() or Remove/At() statement in your code.

这篇关于退出表单之前,我是否需要处理动态创建的控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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