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

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

问题描述

如果您遇到了一些C#code这样的使用语句/资源嵌套:

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在),如果将递归地处置其子女的你,或者你需要明确地处理每个层,独立使用的语句?例如。如果你的配置BinaryReader在,是否应该处理响应流,这反过来又部署了回应?思考这最后一句话让我觉得你其实需要单独使用的语句,因为没有办法保证一个包装对象将处理内部对象的。是吗?

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?

推荐答案

您需要单独使用的语句。

You need the separate using statements.

在你的第二个例子中,只有 BinaryReader在将得到处置,不能用来构造它的对象。

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

为了明白为什么,看看using语句的实际执行。这需要你的第二个code,并做了等价于:

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

正如你所看到的,永远不会有一个的Dispose()呼吁响应 ResponseStream

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

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