为什么我的FileStream对象被设置的时候,我和QUOT的;使用" BinaryReader在一个对象? [英] Why is my FileStream object being disposed of when I'm "using" a BinaryReader object?

查看:157
本文介绍了为什么我的FileStream对象被设置的时候,我和QUOT的;使用" BinaryReader在一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的函数:

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

一个FileStream对象传入作为参数,BinaryReader在一个与using语句声明。当我尝试使用FileStream对象,调用此函数后,它抛出一个System.ObjectDisposedException。这是为什么FileStream对象被设置的一起物体BinaryReader在?

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?

推荐答案

这是一个很好的问题,我不知道为什么就决定,这是应该的,但很可惜它被证明是这样的方式:

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在类

BinaryReader class

关闭:关闭当前读者的和底层流

如果你看看这个答案这个问题我如何叉在.NET中的流? 那么你会发现他是指一类在一个名为 MiscUtil 该库被称为NonClosingStreamWrapper @ 乔恩斯基特写,你可以用周围的流换到prevent它被封闭。

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();
    }
}

这篇关于为什么我的FileStream对象被设置的时候,我和QUOT的;使用" BinaryReader在一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆