难道还有比嵌套&QUOT更好地确定处置模式;使用" S? [英] Is there a better deterministic disposal pattern than nested "using"s?

查看:87
本文介绍了难道还有比嵌套&QUOT更好地确定处置模式;使用" S?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,如果我想明确地清理非托管资源,我可以使用使用关键字。但对于多个依赖对象,这最终会越走越嵌套:

In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword. But for multiple dependent objects, this ends up nesting further and further:

using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
    using (BufferedStream bs = new BufferedStream(fs))
    {
        using (StreamReader sr = new StreamReader(bs))
        {
            // use sr, and have everything cleaned up when done.
        }
    }
}

在C ++中,我用于能够使用析构函数来做到这一点是这样的:

In C++, I'm used to being able to use destructors to do it like this:

{    
    FileStream fs("c:\file.txt", FileMode.Open);
    BufferedStream bs(fs);
    StreamReader sr(bs);
    // use sr, and have everything cleaned up when done.
}



有没有在C#中的更好的方式来做到这一点? ?还是我坚持了嵌套的多层次

Is there a better way in C# to do this? Or am I stuck with the multiple levels of nesting?

推荐答案

您不必多usings窝:

You don't have to nest with multiple usings:

using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
    // all three get disposed when you're done
}

这篇关于难道还有比嵌套&QUOT更好地确定处置模式;使用" S?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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