gpt4 book ai didi

c# - 如果 using block 返回,是否会释放 IDisposable?

转载 作者:太空狗 更新时间:2023-10-29 21:10:35 26 4
gpt4 key购买 nike

例如

using(var something = GetSomething())
{
something.DoSomething();
if(something.IsX()) return true;
}
return false;

最佳答案

是的,绝对是。 Dispose 方法被调用,但是 using 语句被执行,除非它是一个突然的整个进程终止。最常见的情况是:

  • block 内的返回
  • block 内抛出(但未捕获)异常
  • 自然地到达街区的尽头

基本上 using 语句主要是 try/finally block 的语法糖 - 而 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.

关于c# - 如果 using block 返回,是否会释放 IDisposable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6356307/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com