C Sharp中的流数组 [英] array of streams in c sharp

查看:102
本文介绍了C Sharp中的流数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我在using语句内声明流,以确保在使用完流后正确处理该流,以便当我不在using块外时也不会错误地调用它.

Typically I declare streams inside of a using statement to ensure that the stream is properly disposed when I am done with it, and so that I don't mistakenly call it when I'm outside the using block.

这里有一些例子:使用语句引用的MSDN

如何将using语句与流数组一起使用?等同于在try/catch/finally块之外声明数组,并在finally块中调用每个流的dispose方法?

How does one use a using statement with an array of streams? Would it be equivalent to declare the array outside of a try/catch/finally block and call each stream's dispose method in the finally block?

最后,如何测试流已被正确处置?

Lastly, how does one test that the streams have been properly disposed?

推荐答案

我将创建一个新对象,在其中保存流.像这样的东西(不完全充实):

I would create a new object that holds the Streams in it. Something like this (not totally fleshed out):

class StreamHolder : IDisposable
{
  List<Stream> Streams {get;}

  public void  Dispose()
  {
      Streams.ForEach(x=>x.Dispose()):
  }
}

这样,您可以将容器对象放入 using 语句中,它将为您处理流.您的另一个选择是在Final代码块中处理它,但是如果我要在一个以上的位置中进行处理,我希望将其封装起来,这样我就不会意外地忘记在完成后丢弃所有流..

This way you can put the container object in the using statment, it will will handle the stream disposal for you. Your other option is the handle it in the Finally block, but if I were going to do this in more than one place, I would like to encapsulate it, so I don't accidentally forget to dispose of all the streams when I am done.

这篇关于C Sharp中的流数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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