.NET - Replacing nested using statements with single using statement

后端 未结 5 795
说谎
说谎 2021-01-12 19:08

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

using (var response = (HttpWebResponse)request.GetResponse())
{
    using (         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-12 19:33

    You need the separate using statements.

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

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

提交回复
热议问题