Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在streamwriter、streamreader之前使用语句的好处/用途_C#_Using Statement - Fatal编程技术网

C# 在streamwriter、streamreader之前使用语句的好处/用途

C# 在streamwriter、streamreader之前使用语句的好处/用途,c#,using-statement,C#,Using Statement,可能重复: 所以我刚刚注意到,在msdn示例和一些stackoverflow问题中,在streamwriter等之前使用using语句的地方有答案,但实际的好处是什么?因为我从来没有被教过/告诉过/读过任何使用它的理由 using (StreamReader sr = new StreamReader(path)) { while (sr.Peek() >= 0)

可能重复:

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

            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());

using块调用自动使用的对象的
Dispose
方法,其优点是保证调用它。因此,不管语句块中是否抛出异常,都会释放该对象。它被汇编成:

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

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

using语句适用于实现IDisposable接口的内容

.net将保证StreamReader将被处置


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

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

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

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

它实际上被编译成一个try finally块。@DanielHilgarth绝对正确。我正在编辑答案。@csharpstuent这取决于
IDisposable
的实现方式。它通常释放使用的资源。在我们的
StreamReader
示例中,再次尝试从流中读取将导致此类异常。请注意,已处理的对象不同于
null
对象。@首先,您会注意到一些症状,例如速度过慢等。然后使用探查器(如RedGate的ANTS内存探查器)您可以看到一些大对象从未被垃圾收集或处理。代码还有另一个细节-在using块中,对保存一次性对象的变量执行赋值是无效的,而在上面的代码中,没有任何东西可以阻止从
try
块内更改
sr
的值。