多次使用块,这段代码安全吗?
Multiple using block, is this code safe?
代码片段如下
public static string ToCompressedBase64(this string text)
{
using (var memoryStream = new MemoryStream())
{
using (var gZipOutputStream = new GZipStream(memoryStream, CompressionMode.Compress))
{
using (var streamWriter = new StreamWriter(gZipOutputStream))
{
streamWriter.Write(text);
}
}
return Convert.ToBase64String(memoryStream.ToArray());
}
}
据我所知,如果 class 包含 IDisposable 字段,那么它应该实现 IDisposable 本身并负责处置所拥有的对象,因此根据这个假设,在处置 streamWriter 之后,gZipOutputStream 和memoryStream 也将被释放。但是我们仍然不需要释放memoryStream来调用它的toArray()方法。
所以问题是,最后在 memoryStream 上调用 ToArray() 方法安全吗?
如果我对你的问题的理解正确,你是在问在 MemoryStream
被处理后调用 ToArray()
是否安全。
如果是这样,那么是的,它是安全的。 documentation 指定:
This method works when the MemoryStream
is closed.
编辑:如果不清楚 closed
是否也意味着 disposed
,您还可以查看 source code Dispose
方法(注意:link 是 Stream.Dispose()
因为 MemoryStream
不会覆盖 Dispose
方法):
public void Dispose()
{
/* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
Contract.Ensures(CanRead == false);
Contract.Ensures(CanWrite == false);
Contract.Ensures(CanSeek == false);
*/
Close();
}
如您所见,调用 Dispose()
无非是调用 Close()
.
代码片段如下
public static string ToCompressedBase64(this string text)
{
using (var memoryStream = new MemoryStream())
{
using (var gZipOutputStream = new GZipStream(memoryStream, CompressionMode.Compress))
{
using (var streamWriter = new StreamWriter(gZipOutputStream))
{
streamWriter.Write(text);
}
}
return Convert.ToBase64String(memoryStream.ToArray());
}
}
据我所知,如果 class 包含 IDisposable 字段,那么它应该实现 IDisposable 本身并负责处置所拥有的对象,因此根据这个假设,在处置 streamWriter 之后,gZipOutputStream 和memoryStream 也将被释放。但是我们仍然不需要释放memoryStream来调用它的toArray()方法。
所以问题是,最后在 memoryStream 上调用 ToArray() 方法安全吗?
如果我对你的问题的理解正确,你是在问在 MemoryStream
被处理后调用 ToArray()
是否安全。
如果是这样,那么是的,它是安全的。 documentation 指定:
This method works when the
MemoryStream
is closed.
编辑:如果不清楚 closed
是否也意味着 disposed
,您还可以查看 source code Dispose
方法(注意:link 是 Stream.Dispose()
因为 MemoryStream
不会覆盖 Dispose
方法):
public void Dispose()
{
/* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
Contract.Ensures(CanRead == false);
Contract.Ensures(CanWrite == false);
Contract.Ensures(CanSeek == false);
*/
Close();
}
如您所见,调用 Dispose()
无非是调用 Close()
.