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);
}
}
这篇关于避免处理底层流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:避免处理底层流
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01