为什么当我“使用”时我的 FileStream 对象被释放? BinaryReader 对象?

发布于 2024-10-21 13:28:34 字数 421 浏览 8 评论 0原文

考虑以下函数:

    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 技术交流群。

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

发布评论

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

评论(2

几味少女 2024-10-28 13:28:34

这是一个非常好的问题,我不知道为什么决定应该是这样的,但遗憾的是它被记录为这样:

BinaryReader

关闭:关闭当前读取器和底层流

如果您查看此答案问题 如何在 .NET 中“分叉”流? 然后你会看到他引用了一个名为 MiscUtilJon Skeet 所写的 a> 可以用来环绕流以防止其被关闭。

您可以像这样使用它(对于您的示例):

private int GetSomethingFromFile(FileStream fs) 
{
    using (var wrapper = new NonClosingStreamWrapper(fs))
    using (BinaryReader br = new BinaryReader(wrapper))
    {
        fs.Seek(0, SeekOrigin.Begin);
        return br.ReadInt32();
    }
}

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

Close: Closes the current reader and the underlying stream.

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):

private int GetSomethingFromFile(FileStream fs) 
{
    using (var wrapper = new NonClosingStreamWrapper(fs))
    using (BinaryReader br = new BinaryReader(wrapper))
    {
        fs.Seek(0, SeekOrigin.Begin);
        return br.ReadInt32();
    }
}
哭了丶谁疼 2024-10-28 13:28:34

因为处置二进制读取器就处置了其底层流。

请在调用方方法中使用“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.

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