避免处置底层流 [英] Avoiding dispose of underlying stream

查看:145
本文介绍了避免处置底层流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图嘲弄一些文件操作。在真实的对象,我有:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆