Does calling Clear disposes the items also?

前端 未结 4 1597
予麋鹿
予麋鹿 2021-01-07 19:54

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

Like,

toolStripMenuItem.DropDown         


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-01-07 20:29

    Q: Does?

    A: No - Clear does not dispose the items (they could be used in other parts of your application).

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

    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.

    Read a propos this and this.

    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

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

提交回复
热议问题