.NET:使用块与调用.Dispose使用()NET、Dispose

2023-09-02 01:30:48 作者:゛若無其事的安靜°

据我的理解是,在.NET中的使用语句调用一个IDisposable的对象的.Dispose()方法一旦code退出该块。

It has been my understanding that the using statement in .NET calls an IDisposable object's .Dispose() method once the code exits the block.

请问using语句要做什么吗?如果不是,又好像以下两个code样品达到同样的事情:

Does the using statement do anything else? If not, it would seem that the following two code samples achieve the exact same thing:

Using Con as New Connection()
    Con.Open()
    'do whatever
End Using

Dim Con as New Connection()
Con.Open()
'do whatever
Con.Dispose()

我会以最好的答案谁证实我是正确的还是指出,我错了,并解释了原因。请记住,我知道某些类别的可以做不同的事情的在他们的.Dispose()方法。这个问题是关于使用语句是否达到完全相同的结果与调用对象的.Dispose()方法。

I will give the best answer to whoever confirms that I am correct or points out that I am wrong and explains why. Keep in mind that I am aware that certain classes can do different things in their .Dispose() methods. This question is about whether or not the using statement achieves the exact same result as calling an object's .Dispose() method.

推荐答案

使用基本上是等价的:

try
{
  // code
}
finally
{
  obj.Dispose();
}

所以它也有打电话的利益的Dispose()即使未处理的异常被抛出块内的code。

So it also has the benefit of calling Dispose() even if an unhandled exception is thrown in the code within the block.