将一个IDisposable的处置,如果使用块的回报? [英] Will a IDisposable be disposed if the using block returns?

查看:98
本文介绍了将一个IDisposable的处置,如果使用块的回报?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

 使用(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 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.

这篇关于将一个IDisposable的处置,如果使用块的回报?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆