将一个IDisposable的处置,如果使用块的回报?IDisposable

2023-09-04 23:59:42 作者:放学铃才是中国好声音

例如

 使用(VAR东西= GetSomething())
{
    something.DoSomething();
    如果(something.IsX())返回true;
}
返回false;
 

解决方案

是的,绝对。该处置方法被调用但是在执行使用语句,除非这是一个突然的全过程结束。最常见的情况是:

A 返回块内的 在抛出异常(而不是抓)块内 接触块的结尾自然

基本上是一个使用语句主要是语法糖为尝试 / 最后块 - 和最后具有相同的所有属性。

编辑:从的 C#4规格:

  

A 使用语句stranslated分为三个部分:获取,使用和处置。资源的使用是隐式的由尝试语句,其中包括最后条款。这最后第处置的资源。

最后语句在规范的第8.10描述:

  

最后块中的语句总是被执行时,在控制离开尝试语句。这是真实的,不管该控制传输正常执行的结果;作为执行破发的结果继续 GOTO 返回语句;或为传播例外出来的结果是尝试语句。

关于骗局 投资7万块钱,3年后有1000万元的回报

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 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.