为什么我的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 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();
}
}