using我对使用关键字有一些疑问。我有以下代码:
try {
   using (System.Net.WebResponse response = httpWebRequest.GetResponse()) {
      throw new Exception("Example");
   }
} 
catch ( Exception ex ) { 
}
我的问题是,当异常发生时它会关闭连接吗?还是我必须关闭 catch 内的连接?
using我对使用关键字有一些疑问。我有以下代码:
try {
   using (System.Net.WebResponse response = httpWebRequest.GetResponse()) {
      throw new Exception("Example");
   }
} 
catch ( Exception ex ) { 
}
我的问题是,当异常发生时它会关闭连接吗?还是我必须关闭 catch 内的连接?
是的,它将关闭连接。
a 的全部意义using在于,当您离开 的范围时,它会处理该对象using,即使它是通过异常处理的。
using块在底层是使用块实现的try/finally。
这也很容易进行实验测试:
public class Foo : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("I was disposed!");
    }
}
private static void Main(string[] args)
{
    try
    {
        using (var foo = new Foo())
            throw new Exception("I'm mean");
    }
    catch { }
 }
输出是:
我被处置了!