是否“使用”了陈述总是处置对象? [英] Does "using" statement always dispose the object?

查看:66
本文介绍了是否“使用”了陈述总是处置对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用语句是否总是处置对象,即使有返回值或在其中引发了异常? IE:

Does the using statement always dispose the object, even if there is a return or an exception is thrown inside it? I.E.:

using (var myClassInstance = new MyClass())
{
    // ...
    return;
}

using (var myClassInstance = new MyClass())
{
    // ...
    throw new UnexplainedAndAnnoyingException();
}


推荐答案

是的,这就是重点。编译为:

Yes, that's the whole point. It compiles down to:

SomeDisposableType obj = new SomeDisposableType();
try
{
    // use obj
}
finally
{
    if (obj != null) 
        ((IDisposable)obj).Dispose();
}

请注意此处的术语;对象本身未释放。调用 Dispose()方法,通常释放非托管资源。

Be careful about your terminology here; the object itself is not deallocated. The Dispose() method is called and, typically, unmanaged resources are released.

这篇关于是否“使用”了陈述总是处置对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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