例如
使用(VAR东西= GetSomething())
{
something.DoSomething();
如果(something.IsX())返回true;
}
返回false;
解决方案
是的,绝对。该处置
方法被调用但是在执行使用
语句,除非这是一个突然的全过程结束。最常见的情况是:
返回
块内的
在抛出异常(而不是抓)块内
接触块的结尾自然
基本上是一个使用
语句主要是语法糖为尝试
/ 最后
块 - 和最后
具有相同的所有属性。
编辑:从的 C#4规格:
A 使用
语句stranslated分为三个部分:获取,使用和处置。资源的使用是隐式的由尝试
语句,其中包括最后
条款。这最后
第处置的资源。
在最后
语句在规范的第8.10描述:
在最后
块中的语句总是被执行时,在控制离开尝试
语句。这是真实的,不管该控制传输正常执行的结果;作为执行破发的结果
,继续
, GOTO
或返回
语句;或为传播例外出来的结果是尝试
语句。
For example
using(var something = GetSomething())
{
something.DoSomething();
if(something.IsX()) return true;
}
return false;
解决方案
Yes, absolutely. The Dispose
method is called however the using
statement is executed, unless it was an abrupt whole-process termination. The most common cases are:
return
within the block
An exception being thrown (and not caught) within the block
Reaching the end of the block naturally
Basically a using
statement is mostly syntactic sugar for a try
/finally
block - and finally
has all the same properties.
EDIT: From section 8.13 of the C# 4 specification:
A using
statement is stranslated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try
statement that includes a finally
clause. This finally
clause disposes of the resource.
The finally
statement is described in section 8.10 of the specification:
The statements of a finally
block are always executed when control leaves a try
statement. This is true whether the control transfer occurs as a result of normal execution; as a result of executing a break
, continue
, goto
or return
statement; or as a result of propagating an exception out of the try
statement.