WinForms 对话框窗体——关闭还是处置? [英] WinForms Dialog Form -- Close or Dispose?

查看:30
本文介绍了WinForms 对话框窗体——关闭还是处置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了一些代码,想由你们来运行这个修改,我关心的是内存管理.

I've inherited some code and wanted to run this modification by you all, my concern is memory management.

假设我有一个基本"表单,其中包含一堆用于打开对话框"表单的按钮.打开对话框表单的推荐模式是什么?目前我们像这样显示对话框"表单(在基本"表单代码中,点击按钮时):

Let us say I have a "base" Form with a bunch of buttons that open "dialog" forms. What is the recommended pattern for opening the dialog forms? Currently we display the "dialog" form like so (in the "base" Form code, upon button click):

ChangePasswordForm frm = new ChangePasswordForm();
frm.ShowDialog();

然后像这样关闭它(在对话框"表单代码中):

Then close it like so (in the "dialog" form code):

private void bCancel_Click(object sender, EventArgs e)
{
  this.Close();
  //this.Dispose();  <-- this is what I am considering adding.
}

我添加 Dispose 的理由是我担心如果每次创建表单的 实例并且它的资源从未真正释放时,此表单是否多次显示和关闭 - 是这个正确吗?另外,如果表单右上角有关闭"X,我是否也应该在 FormClosed 事件中放置一个 Dispose() 调用?

My rationale for adding Dispose is that I am worried if this form is displayed and closed many times that each time a new instance of the form is created and its resources are never really released -- is this correct? Also, if the form has the "close" X in the top right, should I put a Dispose() call in the FormClosed event as well?

提前致谢.

推荐答案

我会使用 using 语句:

  using (var frm = new ChangePasswordForm()) {
      frm.ShowDialog();
  }

将其与 DialogResult 结合起来:

Combine this with a DialogResult:

private void bCancel_Click(object sender, EventArgs e)
{
   this.DialogResult = DialogResult.Cancel;
}

设置DialogResult,会关闭Dialog,调用者/所有者有一些反馈.

Setting the DialogResult, will close the Dialog, and the caller/owner has some feedback.

而且您不必担心 Close 或 Dispose.

And you don't have to worry about Close or Dispose.

这篇关于WinForms 对话框窗体——关闭还是处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆