加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:35:57 所属栏目:百科 来源:网络整理
导读:例如 using(var something = GetSomething()){ something.DoSomething(); if(something.IsX()) return true;}return false; 解决方法 是的,一点没错.调用Dispose方法然后执行using语句,除非它是一个突然的整个进程终止.最常见的情况是: 块内的返回 块内抛出
例如
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读