gpt4 book ai didi

c# - 为什么嵌套的 using block 会多次处理对象?

转载 作者:行者123 更新时间:2023-11-30 13:16:43 24 4
gpt4 key购买 nike

<分区>

为什么嵌套的using block 会多次处置一个对象?

引用CA2202 :

In the following example, a Stream object that is created in an outer using statement is released at the end of the inner using statement in the Dispose method of the StreamWriter object that contains the stream object. At the end of the outer using statement, the stream object is released a second time. The second release is a violation of CA2202.

using (Stream stream = new FileStream("file.txt", FileMode.OpenOrCreate))
{
using (StreamWriter writer = new StreamWriter(stream))
{
// Use the writer object...
}
}

我知道在大多数情况下我可以使用

using ()
using ()
{ }

当我做不到时,我很乐意恢复到 try finally 就像它建议的那样,我只是想知道为什么它适用于 way。

这是否只是生成代码的最佳解释方式,“好的,因为 using block 正在关闭,让我处理所有对象。”还是它以这种方式工作的原因?

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