调用Clear是否也处理项目? [英] Does calling Clear disposes the items also?

查看:153
本文介绍了调用Clear是否也处理项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多时候,有一个清晰的方法,从集合中删除所有的项目,这些项目也处置。

Many times there is a clear method, that removes all the items from the collections, are these items disposed also.

喜欢,

toolStripMenuItem.DropDownItems.Clear();

就足够了,或者我应该像这样调用:

is sufficient, or should I have to call like that:

foreach (ToolStripItem item in toolStripMenuItem.DropDownItems)
{
  toolStripMenuItem.DropDownItems.Remove(item);
  item.Dispose();
}

编辑:Well ToolStripItem是一个例子,不是一个问题,足够我找到另一个例子,TabControl也有项目集合和清除方法。但TabControls可以有复杂的控制(至少我有),需要显式Dispose(即使他们在某些时候被GC自动处置,因为他们需要巨大的内存)。我想最好的答案是divo评论处置项目,然后调用清除。

Well ToolStripItem is an example not a question, for those who says Clear is enough I found another example, TabControl has also item collection and clear method. But TabControls can have complex controls (at least I have), which needs to be explicitly Dispose (even if they are Disposed automatically at some point by GC, cause they take huge memory). I guess the best answer is divo comment to dispose the items, and then call clear.

推荐答案

A: - 清除

所以,如果你的ToolStripItems是标准的.NET,应该清除足够了吗?一些反射后,我会说可能不是。

So, if your ToolStripItems are standard .NET ones, should Clear be sufficient? After some reflection I'd say "probably not".

是的,这是真的,如果你将有任何引用ToolStripItem在应用程序的其他部分, .NET GarbageCollector 会自动销毁(使用类 destructor )。但是,不会调用 Dispose(true) 方法 code> IDisposable 组件。

Yeah, this is true that if you will have any references to the ToolStripItem in other part of your application, the .NET GarbageCollector will destroy(use the class destructor) it automatically. But, it will not call the Dispose(true) method, that is, however, required for the form's IDisposable components.

阅读提议 this and this

实际上,我相信你需要明确 Dispose 您的项目,如ToolStrip的 Dispose 方法( 替换 ):

Actually, I believe that you will, however, need to explicitly Dispose your Items, like the ToolStrip's Dispose method does (replace this by yourToolStrip):

if (!this.Items.IsReadOnly)
{
    for (int i = this.Items.Count - 1; i >= 0; i--)
    {
        this.Items[i].Dispose();
    }
    this.Items.Clear();
}



EDIT



我还创建了以下主题,以阐明这个问题更一般。

EDIT

I also created the following thread to clarify this question more generally.

这篇关于调用Clear是否也处理项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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