这是一个更好的方式来调用Form.ShowDialog()? [英] Which is a better way to call Form.ShowDialog()?

查看:249
本文介绍了这是一个更好的方式来调用Form.ShowDialog()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个更好的方式来显示一个模式对话框?

  Form1中FRM =新Form1中();
frm.showDialog()
 

 (新窗口1())的ShowDialog()。
 

解决方案

无论是其中一个比另一个更好;他们是完全相等的!

然而,在这种特殊情况下,两者都是错误。 需要您致电 的ShowDialog 方法在处置方法,在窗体上。不同于显示关闭的组合,这不是自动完成的。从MSDN:

  

当一个表单显示为一个模式对话框,单击关闭按钮(在窗体的右上角的X按钮)导致表单被隐藏,DialogResult属性设置为 DialogResult.Cancel 。与非模态形式,在关闭方法并不由.NET Framework当用户点击对话框中的关闭表单按钮或设置<$的值称为C $ C>的DialogResult 属性。代替的形式被隐藏,可以再次显示而不产生对话框的新实例。因为显示一个对话框形式是隐藏的,而不是封闭的,则必须调用表单时不再需要由应用程序的形式的处置方法。

因此​​,你应该对这些(当量)的形式之一之间进行选择:

 使用(Form1的FRM =新Form1中())
{
    frm.ShowDialog();
}
 

  Form1中FRM =新Form1中();
frm.ShowDialog();
frm.Dispose();
 

而之所以的ShowDialog 不会自动配置的形式很简单,如果不立即明显。事实证明,应用程序通常希望从一个模式对话框形式的一个实例读取值的的形式已关闭,比如在窗体的控件指定的设置。如果表单进行自动处理,您将无法通过窗体对象的属性来读取这些值。因此,程序员负责显示为模态对话框的形式处理,当他(她)完成它们。

Which is a better way to show a modal dialog?

form1 frm=new form1();
frm.showDialog()

or

(new form1()).showDialog();

解决方案

Neither one is "better" than the other; they are perfectly equivalent!

However, in this particular case, both are wrong. The ShowDialog method requires you to call the Dispose method on the form. Unlike the Show and Close combination, this is not done automatically. From MSDN:

When a form is displayed as a modal dialog box, clicking the Close button (the button with an X at the upper-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel. Unlike non-modal forms, the Close method is not called by the .NET Framework when the user clicks the close form button of a dialog box or sets the value of the DialogResult property. Instead the form is hidden and can be shown again without creating a new instance of the dialog box. Because a form displayed as a dialog box is hidden instead of closed, you must call the Dispose method of the form when the form is no longer needed by your application.

Thus, you should choose between one of these (equivalent) forms:

using (Form1 frm = new Form1())
{
    frm.ShowDialog();
}

or

Form1 frm = new Form1();
frm.ShowDialog();
frm.Dispose();

The reason that ShowDialog doesn't automatically dispose the form is simple enough, if not immediately obvious. It turns out that applications often wish to read values from an instance of a modal dialog form after the form has been closed, such as settings specified in the form's controls. If the form were automatically disposed, you would be unable to read those values by accessing properties of the form object. Thus, the programmer is responsible for disposing forms shown as modal dialogs when (s)he is finished with them.

这篇关于这是一个更好的方式来调用Form.ShowDialog()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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