本文介绍了是否有必要与IDisposable的对象巢usings?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定要包我所有的的IDisposable 对象使用(){} 语句,即使我'米刚好路过一个到另一个?例如,在下面的方法:





公共静态字符串ReadResponse(HttpWebResponse响应)
{
字符串RESP = NULL;
使用(流responseStream = response.GetResponseStream())
{使用
(StreamReader的responseReader =新的StreamReader(responseStream))
{
RESP = responseReader.ReadToEnd( );
}
}
返回RESP;
}



我能巩固这只是一个使用是这样的:



公共静态字符串ReadResponse(HttpWebResponse响应)
{
字符串RESP = NULL;使用
(StreamReader的读者=新的StreamReader(response.GetResponseStream()))
{
RESP = reader.ReadToEnd();
}
返回RESP;
}



我能指望两个的StreamReader 布置?还是我必须使用两个使用语句?


解决方案

是,您可以,但那是因为StreamReader的构造文档特别说:StreamReader对象调用Dispose时StreamReader.Dispose被称为提供Stream对象的



如果没有,那么你可以做这样的事情至少清理代码位。

 使用(流responseStream = response.GetResponseStream())使用
(StreamReader的responseReader =新的StreamReader(responseStream))
{
RESP = responseReader.ReadToEnd() ;
}


Do I have to wrap all my IDisposable objects in using(){} statements, even if I'm just passing one to another? For example, in the following method:

public static string ReadResponse(HttpWebResponse response)
{
    string resp = null;
    using (Stream responseStream = response.GetResponseStream())
    {
        using (StreamReader responseReader = new StreamReader(responseStream))
        {
            resp = responseReader.ReadToEnd();
        }
    }
    return resp;
}

Could I consolidate this to just one using like this:

public static string ReadResponse(HttpWebResponse response)
{
    string resp = null;
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        resp = reader.ReadToEnd();
    }
    return resp;
}

Can I count on both the Stream and the StreamReader being disposed? Or do I have to use two using statements?

解决方案

Yes, you can, but that's because the StreamReader constructor documentation specifically says: "The StreamReader object calls Dispose on the provided Stream object when StreamReader.Dispose is called."

If it didn't, then you could do something like this to at least clean up the code a bit.

using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseReader = new StreamReader(responseStream))
{
    resp = responseReader.ReadToEnd();
}

这篇关于是否有必要与IDisposable的对象巢usings?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 13:12