您通常不能覆盖表单的 Dipose 方法,因为它已经在 Form.Designer.cs 文件中定义。有一个小技巧如何将您自己的处理逻辑添加到表单中。
使用以下类:
public class Disposer : Component
{
private readonly Action<bool> disposeAction;
public Disposer(Action<bool> disposeAction)
{
this.disposeAction = disposeAction;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
this.disposeAction(disposing);
}
public static Disposer Register(ref IContainer container, Action<bool> disposeAction)
{
Disposer disposer = new Disposer(disposeAction);
if (container == null)
container = new System.ComponentModel.Container();
container.Add(disposer);
return disposer;
}
}
保留子表单列表并将以下行添加到主表单的构造函数中:
Disposer.Register(ref this.components, this.MyDisposeAction);
当您的主窗体被释放时,您的所有子窗体也将被释放,例如:
private void MyDisposeAction(bool disposing)
{
if (disposing)
{
foreach (var subForm in this.subForms)
{
subForm.Dispose(disposing);
}
}
}