在C#中,如果我想确定性地清理非托管资源,我可以使用"using"关键字.但是对于多个依赖对象,这最终会进一步嵌套:
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++中,我习惯于使用析构函数来执行此操作:
{ FileStream fs("c:\file.txt", FileMode.Open); BufferedStream bs(fs); StreamReader sr(bs); // use sr, and have everything cleaned up when done. }
在C#中有更好的方法吗?还是我坚持多层次的嵌套?
您不必嵌套多个使用:
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 }
您可以在开头大括号之前将using语句放在一起,如下所示:
using (StreamWriter w1 = File.CreateText("W1")) using (StreamWriter w2 = File.CreateText("W2")) { // code here }
http://blogs.msdn.com/ericgu/archive/2004/08/05/209267.aspx