Is there a better deterministic disposal pattern than nested “using”s?

前端 未结 10 1420
难免孤独
难免孤独 2021-02-18 18:23

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 furt

10条回答
  •  天涯浪人
    2021-02-18 18:57

    You could use this syntax to condense things down a bit:

    using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
    using (BufferedStream bs = new BufferedStream(fs))
    using (StreamReader sr = new StreamReader(bs))
    {
    }
    

    This is one of those rare occasions where not using { } for all blocks makes sense IMHO.

提交回复
热议问题