我们是否需要在 using 块中关闭 C# BinaryWriter 或 BinaryReader ?
有了这段代码:
using (BinaryWriter writer = new BinaryWriter(File.Open(ProjectPath, FileMode.Create)))
{
//save something here
}
我们需要关闭 BinaryWriter 吗? 如果没有,为什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只要它全部包含在
using
块中,那么您就不需要显式调用Close
。using
块将确保对象被释放,并且Close
和Dispose
方法在BinaryWriter
上可以互换。 (Close
方法只是在后台调用Dispose
。)So long as it's all wrapped up in a
using
block then you don't need to explicitly callClose
.The
using
block will ensure that the object is disposed, and theClose
andDispose
methods are interchangeable onBinaryWriter
. (TheClose
method just callsDispose
behind the scenes.)使用您那里的代码,一旦退出 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.
根据代码示例将其放入 using 语句中将调用 Dispose,这会关闭底层流,所以不会。 您可以通过 Reflector 看到这一点:
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:
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.
通过将编写器包装在 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.