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

前端之家收集整理的这篇文章主要介绍了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.

原文链接:https://www.f2er.com/csharp/244161.html

猜你在找的C#相关文章