Which is a better way to call Form.ShowDialog()?

老子叫甜甜 提交于 2019-12-05 14:28:39

问题


Which is a better way to show a modal dialog?

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

or

(new form1()).showDialog();

回答1:


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.




回答2:


Generally I would go for the first 1 because you can access the form afterwards.

Otherwise the 2nd on is ok, if you dont want to deal with it after it is closed.



来源:https://stackoverflow.com/questions/8624654/which-is-a-better-way-to-call-form-showdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!