在streamwriter,streamreader之前使用声明的好处/使用

时间:2013-01-31 23:35:23

标签: c# using-statement

  

可能重复:
  What is the C# Using block and why should I use it?

所以我刚才注意到在msdn示例和一些stackoverflow问题中有回答,其中using语句在streamwriter等之前使用,但实际上有什么好处?因为我从来没有被教过/告知/读过使用它的任何理由。

            using (StreamReader sr = new StreamReader(path)) 
            {
                while (sr.Peek() >= 0) 
                    Console.WriteLine(sr.ReadLine());
            }

而不是:

            StreamReader sr = new StreamReader(path);
            while (sr.Peek() >= 0) 
                Console.WriteLine(sr.ReadLine());

4 个答案:

答案 0 :(得分:6)

using块调用自动使用的对象的Dispose方法,好的一点是保证可以调用它。因此,无论事件是否在语句块中抛出异常,都会处置该对象。它被编译成:

{
    StreamReader sr = new StreamReader(path);
    try
    {
        while (sr.Peek() >= 0) 
            Console.WriteLine(sr.ReadLine());
    }
    finally
    {
        if(sr != null)
            sr.Dispose();
    }
}

额外的花括号用于限制sr的范围,因此无法从使用块的外部访问它。

答案 1 :(得分:2)

使用提供了一种方便的语法,可确保正确使用IDisposable对象。它被编译成:

StreamReader sr = new StreamReader(path);
try 
{
    while (sr.Peek() >= 0) 
        Console.WriteLine(sr.ReadLine());
} finally
{
    sr.Dispose();
}

As documented on MSDN

答案 2 :(得分:1)

using语句适用于实现IDisposable接口的东西。

.net将保证StreamReader将被处置。

您不必担心进一步关闭或管理它:只需在“使用”范围内使用您需要的内容。

答案 3 :(得分:1)

它会自动为您调用StreamReader.Dispose()方法。如果您选择不使用using关键字,则在运行代码块后最终会得到一个打开的流。如果你想保留一个文件(等)以供继续使用,这是有益的,但如果你不打算在完成时手动处理它,那么这可能是不好的做法。