关于using语句中的c#:MemoryStream-是否需要调用close()

MemoryStream in Using Statement - Do I need to call close()

在using语句中使用内存流时,我需要调用close吗? 例如,这里需要ms.Close()吗?

1
2
3
4
5
6
  using (MemoryStream ms = new MemoryStream(byteArray))
    {  
      // stuff

      ms.Close();
    }


不,这不对。

using确保将调用Dispose(),该调用又调用Close()方法。

您可以假设using语句关闭了所有类型的流。

从MSDN:

When you use an object that accesses unmanaged resources, such as a StreamWriter, a good practice is to create the instance with a using statement. The using statement automatically closes the stream and calls Dispose on the object when the code that is using it has completed.


When using a memory stream in a using statement do I need to call close?

不,您不需要。 它会由.Dispose()方法自动调用:

1
2
3
4
using (MemoryStream ms = new MemoryStream(byteArray))
{  
    // stuff
}