这两者之间的区别是什么?
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
} 不使用*
// Get response
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());发布于 2011-10-23 01:17:08
Using要求应用于它的对象实现IDisposable,并在对象超出using块的作用域时调用IDisposable的Dispose方法(无论它如何离开该作用域...或者通过正常流经的执行,或者如果抛出Exception )。
另一个变种是不好的做法。您与response相关的资源将不会被清除。
请注意,在这两种情况下都不会清理StreamReader。您应该使用内部using块来完成此任务。
发布于 2011-10-23 01:16:39
使用第一种语法时,会在块的末尾自动调用response.Dispose()。
要在using块中包含一个对象,它必须实现IDisposable接口。
尽可能使用using,这样您就不会忘记释放已分配的对象。
https://stackoverflow.com/questions/7861246
复制相似问题