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

前端 未结 10 1670
难免孤独
难免孤独 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:55

    It should be noted that generally when creating stream based off another stream the new stream will close the one being passed in. So, to further reduce your example:

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

提交回复
热议问题