.NET - 用单个 using 语句替换嵌套 using 语句 [英] .NET - Replacing nested using statements with single using statement

查看:21
本文介绍了.NET - 用单个 using 语句替换嵌套 using 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您遇到过类似这样的带有嵌套 using 语句/资源的 C# 代码:

If you came across some C# code like this with nested using statements/resources:

using (var response = (HttpWebResponse)request.GetResponse())
{
    using (var responseStream = response.GetResponseStream())
    {
        using (var reader = new BinaryReader(responseStream))
        {
            // do something with reader
        }
    }
}

用这样的东西替换它安全吗?

Is it safe to replace it with something like this?

using (var reader = new BinaryReader(((HttpWebResponse)request.GetResponse()).GetResponseStream()))
{
    // do something with reader
}

上面的例子只是嵌套的一次性资源的例子,如果使用不完全正确,请见谅.我很好奇当您处理最外层资源(在本例中为 BinaryReader)时,它是否会为您递归处理其子资源,或者您是否需要使用单独的 using 语句显式处理每个层"?例如.如果您处置 BinaryReader,它是否应该处置响应流,而后者又处置响应?考虑到最后一句话让我觉得您实际上确实需要单独的 using 语句,因为无法保证包装器对象会处理内部对象.是吗?

The example above is just an example of nested disposable resources, so forgive me if it's not exactly correct usage. I'm curious if when you dispose the outermost resource (the BinaryReader in this case), if it will recursively dispose its children for you, or if you need to explicitly dispose each "layer" with separate using statements? E.g. if you dispose the BinaryReader, is it supposed to dispose the response stream, which in turn disposes the response? Thinking about that last sentence makes me think you actually do need the separate using statements, because there's no way to guarantee that a wrapper object would dispose of the inner object. Is that right?

推荐答案

您需要单独的 using 语句.

You need the separate using statements.

在你的第二个例子中,只有 BinaryReader 会被释放,而不是用于构造它的对象.

In your second example, only the BinaryReader will get disposed, not the objects used to construct it.

要了解原因,请查看使用声明事实上.它需要您的第二个代码,并执行以下操作:

In order to see why, look at what the using statement actually does. It takes your second code, and does something equivalent to:

{
    var reader = new BinaryReader(((HttpWebResponse)request.GetResponse()).GetResponseStream());
    try
    {
      // do something with reader
    }
    finally
    {
        if (reader != null)
            ((IDisposable)reader).Dispose();
    }
}

如您所见,ResponseResponseStream 上永远不会有 Dispose() 调用.

As you can see, there would never be a Dispose() call on the Response or ResponseStream.

这篇关于.NET - 用单个 using 语句替换嵌套 using 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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