gpt4 book ai didi

c# - using 会在 null 上工作吗?

转载 作者:可可西里 更新时间:2023-11-01 08:02:18 25 4
gpt4 key购买 nike

如果资源没有实现 IDisposable,下面的代码可以工作吗?

  T resource = new T();
using (resource as IDisposable)
{
...
}

最佳答案

是的。 using 语句检查它是否被赋予 null 并避免尝试调用 Dispose 如果是。

来自 C# 3 规范的第 8.13 节:

A using statement is translated 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. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.

关于c# - using 会在 null 上工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/707399/

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