問題描述
我正在嘗試模擬一些文件操作.在我擁有的真實"對象中:
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.
I′m 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);
}
}
這篇關于避免處理底層流的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!