问题描述
据我所知,using 语句 调用 IDisposable
对象的 Dispose()
方法.
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
语句还有其他作用吗?如果没有,以下两个代码示例似乎实现了完全相同的事情:
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()
方法中可以做不同的事情.这个问题是关于 using
语句是否达到与调用对象的 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.
推荐答案
using
基本上相当于:
try
{
// code
}
finally
{
obj.Dispose();
}
因此它也有调用 Dispose()
的好处,即使块内的代码中抛出了未处理的异常.
So it also has the benefit of calling Dispose()
even if an unhandled exception is thrown in the code within the block.
这篇关于使用语句与 IDisposable.Dispose()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!