多次使用块,此代码安全吗? [英] Multiple using block, is this code safe?

查看:75
本文介绍了多次使用块,此代码安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码段如下

 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());
        }
    }

据我所知,如果类包含IDisposable字段,则它应该自己实现IDisposable并照顾拥有对象的处置,因此在此假设下,在处置streamWriter之后,还将处置gZipOutputStream和memoryStream.但是我们仍然不需要配置memoryStream来在它上调用toArray()方法.
因此,问题是,在最后的memoryStream上调用ToArray()方法是否安全?

As far as I know, if class contains field which is IDisposable then It should implement IDisposable itself and take care of disposal of the owned object, so with this assumptions, after disposal of streamWriter the gZipOutputStream and memoryStream will also be disposed. But we still need not disposed memoryStream to invoke toArray() method on It.
So the question is, Is calling ToArray() method on memoryStream at the end safe?

推荐答案

如果我正确理解了您的问题,则您正在询问是否可以安全地在 MemoryStream上调用 ToArray() 处理后.

If I understand your question correctly, you are asking if it's safe to call ToArray() on a MemoryStream after it has been disposed.

如果是这样,那么是安全的.文档指定:

If so, then yes, it's safe. The documentation specifies:

此方法在 MemoryStream 关闭时起作用.

编辑:如果不清楚 closed 是否也意味着 dispose ,您还可以查看

EDIT: And in case it's not clear whether closed also means disposed, you can also look at the source code for the Dispose method (Note: The link is to Stream.Dispose() since MemoryStream doesn't override the Dispose method):

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().

As you can see, calling Dispose() does nothing more than calling Close().

这篇关于多次使用块,此代码安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆