考虑以下函数:
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 对象一起被处理?
这是一个非常好的问题,我不知道为什么决定应该是这样的,但遗憾的是它被记录为这样:
二进制阅读器 http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx class
Close http://msdn.microsoft.com/en-us/library/system.io.binaryreader.close.aspx:关闭当前阅读器和底层流.
如果你签出这个答案 https://stackoverflow.com/questions/1633672/how-do-i-fork-a-stream-in-net/1633835#1633835对这个问题如何在 .NET 中“分叉”流? https://stackoverflow.com/questions/1633672/how-do-i-fork-a-stream-in-net然后你会看到他引用了一个名为 NonClosingStreamWrapper 的类,该类位于名为MiscUtil http://www.yoda.arachsys.com/csharp/miscutil/ that @乔恩·斯基特 https://stackoverflow.com/users/22656/jon-skeet已经写道,您可以使用环绕流来防止它被关闭。
您可以像这样使用它(对于您的示例):
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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)