【发布时间】:2011-01-13 21:29:21
【问题描述】:
简单的问题...
我有一些控件,用户可以在运行时在我的表单上拖动。他们也可以删除它们......当他们点击删除按钮时我应该只打电话给.Dispose();,还是应该做类似panel1.Controls.Clear(Control);的事情? ...还是别的什么?
谢谢:)
贝尔
【问题讨论】:
简单的问题...
我有一些控件,用户可以在运行时在我的表单上拖动。他们也可以删除它们......当他们点击删除按钮时我应该只打电话给.Dispose();,还是应该做类似panel1.Controls.Clear(Control);的事情? ...还是别的什么?
谢谢:)
贝尔
【问题讨论】:
您应该按照 Darin Dimitrov 的回复中所述将其从父 Controls 集合中删除,并调用 Dispose:
panel.Controls.Remove(someControlInstance);
someControlInstance.Dispose();
当您完成对实现 IDisposable 的对象时,您应该始终调用 Dispose,以便立即释放它们拥有的任何非托管资源。
【讨论】:
只需从面板中移除控件即可:
panel.Controls.Remove(someControlInstance);
一旦不再有对它的引用,它将受到垃圾回收,并且非托管资源将被正确处置。
【讨论】:
...the Control class does not behave like any other .NET class. A Control is kept alive by its Handle property. Which stores the native Windows handle. As long as the native window exists, the Control object cannot be destroyed. GC 似乎无法自行处理Control。