问题描述
我正在尝试模拟一些文件操作.在我拥有的真实"对象中:
I'm attempting to mock some file operations. In the "real" object I have:
StreamWriter createFile( string name )
{
return new StreamWriter( Path.Combine( _outFolder, name ), false, Encoding.UTF8 ) );
}
在我希望喜欢的模拟对象中:
In the mock object I'd like to have:
StreamWriter createFile( string name )
{
var ms = new MemoryStream();
_files.Add( Path.Combine( _outFolder, name ), ms );
return new StreamWriter( ms, Encoding.UTF8 ) );
}
其中 _files 是一个字典,用于存储创建的文件以供以后检查.
where _files is a dictionary to store created files for later inspection.
但是,当消费者关闭 StreamWriter 时,它也释放 MeamoryStream... :-(
However, when the consumer closes the StreamWriter, it also disposes the MeamoryStream... :-(
对如何追求这个有什么想法吗?
Any thoughts on how to pursue this?
推荐答案
如果将 MemoryStream 子类化,这将起作用,但您必须调用 ManualDispose 方法来关闭底层流.
我不确定,但我认为这个对象超出范围时会被垃圾回收.
If you subclass the MemoryStream, this will work but you have to call ManualDispose method to close the underlying stream.
Im not sure but I think this object will be garbage-collected when it goes out of scope.
public sealed class ManualMemoryStream : MemoryStream
{
protected override void Dispose(bool disposing)
{
}
public void ManualDispose()
{
base.Dispose(true);
}
}
如果您希望 MemoryStream 被刷新并准备好从顶部读取,这是一种替代方法.
This is an alternative if you want the MemoryStream to be flushed and ready to be read from top.
public sealed class ManualMemoryStream : MemoryStream
{
protected override void Dispose(bool disposing)
{
Flush();
Seek(0, SeekOrigin.Begin);
}
public void ManualDispose()
{
base.Dispose(true);
}
}
这篇关于避免处理底层流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!