Remove TabPage: Dispose or Clear or both?

╄→гoц情女王★ 提交于 2019-12-04 03:42:27

问题


I am working on a windows form that has a TabControl named tabDocuments. I came across this piece of code that removes all pages from the TabControl.

for (int i = tabDocuments.TabPages.Count - 1; i > -1; i--) {
    tabDocuments.TabPages[i].Dispose();
}
    tabDocuments.TabPages.Clear();

The person who wrote this code has already left a while ago. I am trying to understand why the code is calling Clear() after disposing each of the tabPages (looks un-necessary to me). Can anyone please explain to me why? Or is calling Clear() extra?


回答1:


This snippet is from Control.Dispose:

        if (this.parent != null)
        {
            this.parent.Controls.Remove(this);
        }

Therefore you just have to call Dispose, not Clear.




回答2:


Calling Dispose() on each of the tab pages does not actually remove them from the TabPages collection, it simply disposes them. The call to Clear() is what removes them from the collection. If you don't call Clear() they will still be there, and bad things will likely happen because you will end up trying to use them after they have been disposed.




回答3:


First remove a Tab from the collection, then Dispose(). Never Dispose() something that is still in use, as it will cause exceptions and strange behavior.

Also, ensure that no one else have references to the tabs, otherwise those references will become invalid on Dispose().



来源:https://stackoverflow.com/questions/1757116/remove-tabpage-dispose-or-clear-or-both

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!