将一个IDisposable的处置,如果使用块的回报? [英] Will a IDisposable be disposed if the using block returns?
问题描述
例如
使用(VAR东西= GetSomething())
{
something.DoSomething();
如果(something.IsX())返回true;
}
返回false;
是的,绝对。该处置
方法被调用但是在执行使用
语句,除非这是一个突然的全过程结束。最常见的情况是:
- A
返回
块内的 - 在抛出异常(而不是抓)块内
- 接触块的结尾自然
基本上是一个使用
语句主要是语法糖为尝试
/ 最后
块 - 和最后
具有相同的所有属性。
编辑:从的<一节8.13 href="http://download.microsoft.com/download/0/B/D/0BDA894F-2CCD-4C2C-B5A7-4EB1171962E5/CSharp%20Language%20Specification.doc"相对=nofollow> 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:
- A
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 atry
statement that includes afinally
clause. Thisfinally
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 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.
这篇关于将一个IDisposable的处置,如果使用块的回报?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!