我们是否需要在 using 块中关闭 C# BinaryWriter 或 BinaryReader ?

发布于 2024-07-25 21:57:37 字数 200 浏览 4 评论 0 原文

有了这段代码:

using (BinaryWriter writer = new BinaryWriter(File.Open(ProjectPath, FileMode.Create)))
{
   //save something here
}

我们需要关闭 BinaryWriter 吗? 如果没有,为什么?

Having this code:

using (BinaryWriter writer = new BinaryWriter(File.Open(ProjectPath, FileMode.Create)))
{
   //save something here
}

Do we need to close the BinaryWriter? If not, why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

夜吻♂芭芘 2024-08-01 21:57:37

只要它全部包含在 using 块中,那么您就不需要显式调用 Close

using 块将确保对象被释放,并且 CloseDispose 方法在 BinaryWriter 上可以互换。 (Close 方法只是在后台调用 Dispose。)

So long as it's all wrapped up in a using block then you don't need to explicitly call Close.

The using block will ensure that the object is disposed, and the Close and Dispose methods are interchangeable on BinaryWriter. (The Close method just calls Dispose behind the scenes.)

魂归处 2024-08-01 21:57:37

使用您那里的代码,一旦退出 using 块,它将关闭文件,因此您不需要显式调用 close 。

不使用 using 语句的唯一原因是,如果您希望文件在完成 BinaryWriter 后仍然打开,在这种情况下,您应该保留它的引用,而不是像这样将其传递到构造函数中。

With the code you have there it will close the file once it exits the using block, so you do not need to call close explcitly.

The only reason not to use the using statement would be if you want the file to still be open after you are done with your BinaryWriter, in which case you should hold on to a reference of it instead of passing it into the constructor like that.

┈┾☆殇 2024-08-01 21:57:37

根据代码示例将其放入 using 语句中将调用 Dispose,这会关闭底层流,所以不会。 您可以通过 Reflector 看到这一点:

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        this.OutStream.Close();
    }
}

Putting it in a using statement as per your code example will call Dispose, which closes the underlying stream, so no. You can see this through Reflector:

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        this.OutStream.Close();
    }
}
冰雪梦之恋 2024-08-01 21:57:37

using 块将自动关闭二进制编写器并将其置于要进行 GC 的状态。 使用块是用于自己进行异常处理和关闭流的语法糖。

The using block will automaticlly close the binary writer and put it in a state to be GC'ed. Using blocks are syntactic sugar for doing the exception handling and closing of the stream yourself.

几味少女 2024-08-01 21:57:37

通过将编写器包装在 using 块中,当编写器被释放时,关闭将自动发生。 因此在这种情况下,您不需要显式关闭 writer。

By wrapping the writer up in a using block, the close will automatically happen when the writer is disposed. So in this case, you don't need to explicitly close the writer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文