我的理解是,一旦代码退出块,.NET中的.NET调用IDisposable对象的Dispose()方法。
using语句还能做什么吗?如果不是,以下两个代码示例似乎实现了完全相同的目标:
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()方法完全相同的结果。
发布于 2012-06-11 16:52:54
using基本上相当于:
try
{
// code
}
finally
{
obj.Dispose();
}因此,即使在块内的代码中抛出未处理的异常,它也具有调用Dispose()的好处。
发布于 2013-12-29 13:36:42
正如Brian在here中所指出的,它只是try和finally块的一个实现,以确保对象被释放。除了他的答案之外,using块还确保即使使用作用域返回,也会释放对象。
我曾经对此感到好奇,并使用以下方法对其进行了测试:
自定义IDisposable测试类和主
private class DisposableTest : IDisposable
{
public string Name { get; set; }
public void Dispose() { Console.WriteLine("{0}.Dispose() is called !", Name); }
}
public static void Main(string[] args)
{
try
{
UsingReturnTest();
UsingExceptionTest();
}
catch { }
try
{
DisposeReturnTest();
DisposeExceptionTest();
}
catch { }
DisposeExtraTest();
Console.ReadLine();
} 测试用例实现
private static string UsingReturnTest()
{
using (DisposableTest usingReturn = new DisposableTest() { Name = "UsingReturn" })
{
return usingReturn.Name;
}
}
private static void UsingExceptionTest()
{
using (DisposableTest usingException = new DisposableTest() { Name = "UsingException" })
{
int x = int.Parse("NaN");
}
}
private static string DisposeReturnTest()
{
DisposableTest disposeReturn = new DisposableTest() { Name = "DisposeReturn" };
return disposeReturn.Name;
disposeReturn.Dispose(); // # IDE Warning; Unreachable code detected
}
private static void DisposeExceptionTest()
{
DisposableTest disposeException = new DisposableTest() { Name = "DisposeException" };
int x = int.Parse("NaN");
disposeException.Dispose();
}
private static void DisposeExtraTest()
{
DisposableTest disposeExtra = null;
try
{
disposeExtra = new DisposableTest() { Name = "DisposeExtra" };
return;
}
catch { }
finally
{
if (disposeExtra != null) { disposeExtra.Dispose(); }
}
}输出是:
发布于 2012-06-11 18:30:57
//preceeding code
using (con = new Connection()) {
con.Open()
//do whatever
}
//following code相当于以下内容(请注意con的有限范围):
//preceeding code
{
var con = new Connection();
try {
con.Open()
//do whatever
} finally {
if (con != null) con.Dispose();
}
}
//following code这里描述了这一点:http://msdn.microsoft.com/en-us/library/yh598w02.aspx
使用语句确保在调用对象上的方法时发生异常,也会调用Dispose。--您可以通过将对象放入try块中,然后在一个最终块中调用Dispose来实现相同的结果;实际上,编译器.
就是这样翻译using语句的。
https://stackoverflow.com/questions/10984336
复制相似问题