gpt4 book ai didi

c# - Stream.Dispose 是否总是调用 Stream.Close(和 Stream.Flush)

转载 作者:IT王子 更新时间:2023-10-29 03:44:15 32 4
gpt4 key购买 nike

如果我有以下情况:

StreamWriter MySW = null;
try
{
Stream MyStream = new FileStream("asdf.txt");
MySW = new StreamWriter(MyStream);
MySW.Write("blah");
}
finally
{
if (MySW != null)
{
MySW.Flush();
MySW.Close();
MySW.Dispose();
}
}

我是否可以只调用 MySW.Dispose() 并跳过关闭,即使它已提供?是否有任何 Stream implimentations 无法按预期工作(如 CryptoStream)?

如果不是,那么下面就是错误的代码:

using (StreamWriter MySW = new StreamWriter(MyStream))
{
MySW.Write("Blah");
}

最佳答案

Can I just call MySW.Dispose() and skip the Close even though it is provided?

是的,这就是它的用途。

Are there any Stream implementations that don't work as expected (Like CryptoStream)?

可以安全地假设,如果一个对象实现了 IDisposable,它将正确地处理自己。

如果没有,那就是一个错误。

If not, then is the following just bad code:

不,该代码是处理实现 IDisposable 对象的推荐方式。

更多优秀信息在对 Close and Dispose - which to call? 的接受答案中

关于c# - Stream.Dispose 是否总是调用 Stream.Close(和 Stream.Flush),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/911408/

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