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();
} |
-
stackoverflow.com/a/234257/490018
-
可能的配音:stackoverflow.com/questions/911408/
不,这不对。
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.
-
我意识到这已经很老了,但是我想补充一点,除了using以外,还使用.Close()也会导致代码分析警告" CA2202:请勿多次放置对象"。 有关更多信息,请在此处阅读"原因"部分:msdn.microsoft.com/query/
-
是不是相反。 那.Close()会叫.Dispose()吗? msdn.microsoft.com/en-us/library/
-
Dispose()调用Close(),后者调用Dispose(boolean)。
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
} |
-
@HenkHolterman实际上Dispose()调用Close(),而后者又调用Dispose(true)。