加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C#中对同一作用域使用多个using语句时,是否保证调用Dispose()

发布时间:2020-12-16 00:00:51 所属栏目:百科 来源:网络整理
导读:using (Stuff1 stf1 = new Stuff1(...)) // Allocation of stf1using (Stuff2 stf2 = new Stuff2(...)) // Allocation of stf2{ try { // ... do stuff with stf1 and stf2 here ... } catch (Stuff1Exception ex1) { // ... } catch (Stuff2Exception ex2)
using (Stuff1 stf1 = new Stuff1(...)) // Allocation of stf1
using (Stuff2 stf2 = new Stuff2(...)) // Allocation of stf2
{
    try
    {
        // ... do stuff with stf1 and stf2 here ...
    }
    catch (Stuff1Exception ex1)
    {
        // ...
    }
    catch (Stuff2Exception ex2)
    {
        // ...
    }
} // Automatic deterministic destruction through Dispose() for stf1/stf2 - but in which order?

换句话说,是否保证首先调用stf2的Dispose()方法,然后保证stf1的Dispose()方法被调用为秒? (基本上:Dispose()方法是按照它们所属对象的分配顺序调用的吗?)

解决方法

using语句与其他块级语句没有什么不同.如果您编写如下代码:

if (...)
    if (...)
    {

    }

你会清楚地知道发生了什么命令(不是我会建议那个特定的结构),因为它与此完全相同:

if (...)
{
    if(...)
    {

    }
}

所以它是使用.您的代码与以下内容没有区别:

using (...)
{
    using(...)
    {

    }
}

在这里,很明显内部使用块首先终止,因此它的资源应该首先处理.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读