System.IO.StreamWriter:为什么我必须使用关键字"using"

Blu*_*Bug 0 c# text using streamwriter

//C#
using (System.IO.StreamWriter writer = 
    new System.IO.StreamWriter("me00.txt", true))
{
    writer.WriteLine("Hey"); //saved 
}
System.IO.StreamWriter writer02 = new System.IO.StreamWriter("me01.txt", true);
writer02.WriteLine("Now hey x2"); //not saved
Run Code Online (Sandbox Code Playgroud)

创建了文件me00.txt和me01.txt,但只保存了第一个文件的内容.

me00.txt会排队嘿.me01.txt将是一个空的txt文件; "现在嘿x2"没有保存.

关键词"使用"做了什么来引起这种观察?

Cur*_*urt 6

您不必使用"使用".这只是阻止你做更多打字的捷径......

另一种方法是将整个事物嵌套在try-finally结构中,如下所示:

 System.IO.StreamWriter writer = null; 

 try
 {
     writer = new System.IO.StreamWriter("me00.txt", true);
     writer.WriteLine("Hey");
 }
 finally
 {
     if (writer != null)
        writer.Dispose();
 )
Run Code Online (Sandbox Code Playgroud)

当作家被处置时,它也被关闭,这是你缺少的一步.在使用提出了一个整洁的方式做到这一切紧凑.