简体   繁体   中英

C#: “using” when instantiating a form?

I am looking at some C# code written by someone else. Whenever a form is instantiated and then shown, the following is done. Is this correct? Why would you use "using" in this context?

MyForm f;
using (f = new MyForm())
{
    f.ShowDialog();
}

Additional question:

Could the following code be substituted?

using (MyForm f = new MyForm())
{
    f.ShowDialog();
}

WinForms中的Form实现了IDisposable模式(它从Component继承了IDisposable 。原作者正确地确保通过using语句处理该值。

This restricts the resources held by the MyForm object f to the using block. Its Dispose method will be called when the block is exited and it is guaranteed to be "disposed" of at that time. Therefore any resources it holds will get deterministically cleaned up. Also, f cannot be modified to refer to another object within the using block. For more details, see the info about using in MSDN:


using in the C# Reference

Perhaps. If MyForm implements IDisposable, this will ensure that the Dispose method is called if an exception is thrown in the call to ShowDialog.

Otherwise, the using is not necessary unless you want to force disposal immediately

Yes, this is a 'correct' usage of IDisposable. Perhaps the author of MyForm had some large object (say a large MemoryStream) or file resource (eg an open FileStream) that it opened and wanted to make sure was released ASAP. Calling the MyForm ctor inside a using statement would be helpful in this case.

Question 2:

in C# 3.0+, you can use the shorter (and just as clear):

using ( var f = new MyForm())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM