Controls.Clear() 清理的深度有多深? [英] How deep does Controls.Clear() clean up?

查看:34
本文介绍了Controls.Clear() 清理的深度有多深?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个 TableLayoutPanel,它动态地填充了其他 TablelayoutPanels.

I'm using a TableLayoutPanel which is dynamically filled with other TablelayoutPanels.

现在我想知道当我在动态填充的 TableLayoutPanel 上调用 TableLayoutPanel.Controls.Clear 时会发生什么.很明显,所有的子布局都被删除了,但是他们的孩子呢?它们是否也被妥善处理,还是我需要担心内存泄漏?

Now I'm wondering what happens when I call TableLayoutPanel.Controls.Clear on the dynamically filled TableLayoutPanel. Obviously, all the sub-layouts are removed, but how about their children? Are they properly disposed as well or do I need to fear a memory leak?

我应该在调用 Clear() 之前递归删除孩子的孩子吗?

Should I recursively remove the children of the children before calling Clear()?

推荐答案

Clear 不处理控件,导致内存泄漏.来自链接:

Clear doesn't dispose the controls, leading to a memory leak. From the link:

调用 Clear 方法不会从内存中删除控制句柄.您必须显式调用 Dispose 方法以避免内存泄漏.

Calling the Clear method does not remove control handles from memory. You must explicitly call the Dispose method to avoid memory leaks.

由于在循环中处理会弄乱索引,您可以将控件集合复制到另一个列表并对它们执行 ForEach 循环或使用向后的 For 循环.

Since disposing within a loop messes up the indexing, you can either copy the control collection to another list and perform a ForEach loop on them or use a backwards For loop.

 for (int i = myTableLayoutPanelControls.Count - 1; i >= 0; --i) 
    myTableLayoutPanelControls[i].Dispose();
  

调用 Dispose 将从内存中删除控件(当 GC 拾取它时).这也将处理子控件的 Dispose 方法的调用.

Calling Dispose will remove the controls from memory (when the GC picks it up). This will also handle the calling of the child control's Dispose method.

一个问题是,如果您有一个实现 IDisposable 的自定义控件,或者您在不调用 base 的情况下覆盖了 Dispose 方法方法.在对象的 Dispose 方法中,您需要确保已取消订阅范围之外的任何事件.如果不这样做,该引用将使您的对象保持活动状态.

One catch is if you've got a custom control that implements IDisposable or you're overriding the Dispose method without calling the base method. In your object's Dispose method you need to ensure that you've unsubscribed from any events outside your scope. If you don't, that reference will keep your object alive.

这篇关于Controls.Clear() 清理的深度有多深?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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