C#’s using statement provides a syntactic shortcut for calling Dispose on
objects that implement IDisposable, using a try/finally block. For example:
C#的using语句提供了调用Dispose on的语法快捷方式, 相当于使用try/finally块实现IDisposable的对象。例如:
using (FileStream fs = new FileStream ("myFile.txt", FileMode.Open))
{
// ... Write to the file ...
}
// The compiler converts this to 编译器会将上述语句转换为:
FileStream fs = new FileStream ("myFile.txt", FileMode.Open);
try
{
// ... Write to the file ...
}finally
{
if (fs != null) ((IDisposable)fs).Dispose();
}
The finally block ensures that the Dispose method is called even when an
exception is thrown,1 or the code exits the block early.
finally块确保可以执行到Dispose方法,即使在try中抛出异常或代码提前return出来。
上述来源:C#_7.0 in a Nutshell
个人更倾向于使用using,
可以少写try…cath…的嵌套,还不用手动释放资源,避免手动释放前的操作抛异常执行不到释放语句,导致句柄或者文件流没释放,后续使用报文件占用之类的异常:
try{
using (FileStream fs = new FileStream ("myFile.txt", FileMode.Open))
{
// ... Write to the file ...
}
}catch (Exception ex)
{
//这里可以避免FileStream fs = new FileStream ("myFile.txt", FileMode.Open)抛出异常
}