使用块VS IDisposabe.Dispose() [英] Using block vs IDisposabe.Dispose()

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

问题描述

据我的理解,在.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()方法。这个问题是关于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()即使未处理的异常被抛出块内的code。

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

这篇关于使用块VS IDisposabe.Dispose()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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