Using DialogResult Correctly

前端 未结 2 836
野性不改
野性不改 2020-11-30 08:52

In an answer to a recent question I had (Here), Hans Passant stated that I should set the DialogResult to close my forms instead of form.Close() al

2条回答
  •  遥遥无期
    2020-11-30 09:18

    Whether you call Close or set the DialogResult property is not really the issue. You just need to make sure to call Dispose. I prefer doing this with a using block:

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

    I originally thought that you could call ShowDialog on a Form that has already had its Close method called. This is not the case. If you show the form modally with ShowDialog, it doesn't seem to matter whether it is closed as a result of the Close method, or setting the DialogResult property. It would seem that setting the DialogResult is just a short-cut for closing the Form.

    But whether you call Close or set the DialogResult property, the key is to make sure that you call Dispose() or put your form in a using block.

提交回复
热议问题