Avoiding dispose of underlying stream(避免处理底层流)
问题描述
我正在尝试模拟一些文件操作.在我拥有的真实"对象中:
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);
}
}
这篇关于避免处理底层流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:避免处理底层流


- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04