避免处理底层流

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)