首页 > 解决方案 > Winforms OnFormClosing 和 Disposing/Close

问题描述

我有一个表单,我想重写 OnFormClosing 方法。此方法是否需要显式调用 Close 或 Dispose?

这是我的家长表格

public partial class MyParentForm : Form
{

   // Other methods

   public void RunChildForm()
   {
      Hide();

      var child = new MyChildForm()
      {
         Owner = this
      };

      child.Play();
   }

}

这是我的孩子表格

public partial class MyChildForm : Form
{

   // Other methods

   public void Play()
   {
      Show();
   }

   protected override void OnFormClosing(FormClosingEventArgs e)
   {

      // WHAT IS THE CORRECT ORDER?
      // Some code
      ...

      // Display the owner form
      Owner.Show(); 

      base.OnFormClosing(e);

      // Here, is the Form Disposed/Closed? I am unsure if this is necessary.
      Close();
      Dispose();
   }
}

执行顺序应该是什么?我想清理子窗体,然后再次显示父窗体。

标签: c#winformsdispose

解决方案


您可能真的不想“覆盖 OnFormClosing 方法”。

根据您所说的,您最好的选择可能是简单地为“FormClosing”编写一个事件处理程序。

在 Java 领域(至少在 Java 8 之前),您通常会创建一个匿名类来覆盖您想要自定义的方法。

在 C#/.Net 领域——特别是在 Winforms 事件处理程序中——MSVS 使得使用委托变得容易


推荐阅读