避免处理底层流

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);
    }
}

这篇关于避免处理底层流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)