如何在不导致内存泄漏的情况下清除()控件 [英] How to Clear() controls without causing a memory leak

查看:27
本文介绍了如何在不导致内存泄漏的情况下清除()控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读关于 Control.Clear(); 导致内存泄漏(在 MSDN),我想知道:

After reading about Control.Clear(); causing memory leaks (verified at MSDN), I was wondering if:

while (Controls.Count > 0) Controls[0].Dispose();

就足够了,还是我必须递归遍历控件内的所有控件?

will be enough, or do I have to iterate recursively through all controls within controls?

此外,在那之后是否有任何理由执行 Control.Clear(); ?(因为我看到有人在某处说)?

Also, is there any reason to do a Control.Clear(); after that? (as I saw someone saying somewhere)?

谢谢.

推荐答案

发布的代码段是正确的.不需要 Clear(),Control.Dispose() 方法已经从 Controls 集合中删除了控件.这就是它起作用的原因.

The posted snippet is correct. No Clear() is required, the Control.Dispose() method already removes the control from the Controls collection. Which is why it works.

不那么令人担忧的循环版本是:

The less alarming version of the loop is:

 for (int ix = Controls.Count-1; ix >= 0; --ix) Controls[ix].Dispose();

无需遍历控件的子级并处理它们,这已经自动发生了.

No need to iterate through the children of the control and dispose them, that already happens automatically.

这篇关于如何在不导致内存泄漏的情况下清除()控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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