例如
using(var something = GetSomething()) { something.DoSomething(); if(something.IsX()) return true; } return false;
解决方法
是的,一点没错.调用Dispose方法然后执行using语句,除非它是一个突然的整个进程终止.最常见的情况是:
>块内的返回
>块内抛出(并未捕获)异常
>自然地到达块的末尾
基本上,using语句主要是try / finally块的语法糖 – 最后具有所有相同的属性.
编辑:从C# 4 specification的第8.13节:
A
using
statement is stranslated into three parts: acquisition,usage,and disposal. Usage of the resource is implicitly enclosed in atry
statement that includes afinally
clause. Thisfinally
clause disposes of the resource.
finally语句在规范的8.10节中描述:
The statements of a
finally
block are always executed when control leaves atry
statement. This is true whether the control transfer occurs as a result of normal execution; as a result of executing abreak
,continue
,goto
orreturn
statement; or as a result of propagating an exception out of thetry
statement.