使用语句与IDisposable.Dispose() [英] Using statement vs. IDisposable.Dispose()

查看:111
本文介绍了使用语句与IDisposable.Dispose()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解, < .NET中的code>使用语句调用 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.

<语句中的还会执行其他操作吗?如果不是,似乎以下两个代码示例实现了完全相同的事情:

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.

推荐答案

使用基本上等同于:

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆