c# – 如果使用块返回,是否会丢弃IDisposable?

例如
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 a try statement that includes a finally clause. This finally clause disposes of the resource.

finally语句在规范的8.10节中描述:

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.

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么