为什么当我“使用”时我的 FileStream 对象被释放? BinaryReader 对象?
考虑以下函数:
private int GetSomethingFromFile(FileStream fs)
{
using (BinaryReader br = new BinaryReader(fs))
{
fs.Seek(0, SeekOrigin.Begin);
return br.ReadInt32();
}
}
FileStream 对象作为参数传入,并使用 using 语句声明 BinaryReader。当我尝试使用该 FileStream 对象时,在调用此函数后,它会抛出 System.ObjectDisposeException。为什么 FileStream 对象与 BinaryReader 对象一起被处理?
Consider the following function:
private int GetSomethingFromFile(FileStream fs)
{
using (BinaryReader br = new BinaryReader(fs))
{
fs.Seek(0, SeekOrigin.Begin);
return br.ReadInt32();
}
}
A FileStream object is passed in as a parameter and a BinaryReader is declared with a using statement. When I try to use that FileStream object, after calling this function, it throws a System.ObjectDisposedException. Why is that FileStream object being disposed of along with the BinaryReader object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个非常好的问题,我不知道为什么决定应该是这样的,但遗憾的是它被记录为这样:
BinaryReader 类
如果您查看此答案问题 如何在 .NET 中“分叉”流? 然后你会看到他引用了一个名为 MiscUtilJon Skeet 所写的 a> 可以用来环绕流以防止其被关闭。
您可以像这样使用它(对于您的示例):
It is a very good question, and I don't know why it was decided that this was how it should be, but alas it is documented to be this way:
BinaryReader class
If you check out this answer to the question How do I “fork” a Stream in .NET? then you'll see that he refers to a class called NonClosingStreamWrapper in a library called MiscUtil that @Jon Skeet has written that you can use to wrap around the stream to prevent it from being closed.
You would use it like this (for your example):
因为处置二进制读取器就处置了其底层流。
请在调用方方法中使用“using”。
原因是任意的:.NET 类库就是这样实现的。
Because disposing the binary reader disposes its underlying stream.
Use "using" in the caller method instead.
The reason is arbitrary: .NET class library is implemented this way.