c# – Stream.Dispose总是调用Stream.Close(和Stream.Flush)

如果我有以下情况:

StreamWriter MySW = null;
try
{
   Stream MyStream = new FileStream("asdf.txt");
   MySW = new StreamWriter(MyStream);
   MySW.Write("blah");
}
finally
{
   if (MySW != null)
   {
      MySW.Flush();
      MySW.Close();
      MySW.Dispose();
   }
}

我可以调用MySW.Dispose()并跳过关闭,即使它提供了吗?有没有任何Stream implimentations不工作像预期(像CryptoStream)?

如果没有,那么下面只是坏代码:

using (StreamWriter MySW = new StreamWriter(MyStream))
{
   MySW.Write("Blah");
}

Can I just call MySW.Dispose() and
skip the Close even though it is
provided?

是的,这是它的目的。

Are there any Stream implementations
that don’t work as expected (Like
CryptoStream)?

可以安全地假设,如果一个对象实现IDisposable,它会正确处理自己。

如果没有,那就是一个bug。

If not, then is the following just bad
code:

不,该代码是处理实现IDisposable的对象的推荐方式。

更好的信息是在Close and Dispose – which to call?的接受答案

http://stackoverflow.com/questions/911408/does-stream-dispose-always-call-stream-close-and-stream-flush

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – Stream.Dispose总是调用Stream.Close(和Stream.Flush)