C# 使用语句中的 MemoryStream - 我是否需要调用 close()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11968289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MemoryStream in Using Statement - Do I need to call close()
提问by AJM
When using a memory stream in a using statement do I need to call close? For instance is ms.Close() needed here?
在 using 语句中使用内存流时,是否需要调用 close?例如这里需要 ms.Close() 吗?
using (MemoryStream ms = new MemoryStream(byteArray))
{
// stuff
ms.Close();
}
采纳答案by sloth
No, it's not.
不,这不对。
usingensures that Dispose()will be called, which in turn calls the Close()method.
using确保Dispose()将被调用,然后调用该Close()方法。
You can assume that all kinds of Streams are getting closed by the usingstatement.
您可以假设所有类型的 Streams 都被该using语句关闭。
From MSDN:
从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.
当您使用访问非托管资源的对象(例如 StreamWriter)时,一个好的做法是使用 using 语句创建实例。using 语句自动关闭流并在使用它的代码完成时调用对象上的 Dispose。
回答by Darin Dimitrov
When using a memory stream in a using statement do I need to call close?
在 using 语句中使用内存流时,是否需要调用 close?
No, you don't need. It will be called by the .Dispose()method which is automatically called:
不,你不需要。它将.Dispose()被自动调用的方法调用:
using (MemoryStream ms = new MemoryStream(byteArray))
{
// stuff
}

