效益/使用前的StreamWriter,StreamReader的using语句 [英] Benefit/Use of using statement before streamwriter , streamreader

查看:321
本文介绍了效益/使用前的StreamWriter,StreamReader的using语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
什么是C#中使用块我为什么要使用它呢?






所以,我刚才注意到,在MSDN的例子和计算器的一些问题有答案在using语句之前的StreamWriter等使用的,但什么是其实好处?因为我从来没有被教导/说/读任何理由来使用它。

 使用(StreamReader的SR =新的StreamReader(路径))
{
而(sr.Peek()> = 0)
Console.WriteLine(sr.ReadLine());
}



而不是:

  StreamReader的SR =新的StreamReader(路径); 
而(sr.Peek()> = 0)
Console.WriteLine(sr.ReadLine());


解决方案

using块调用自动使用的对象,而好点的处置方法是,它保证被调用。所以对象不管事实的异常陈述或者不是块抛出处置。它被编译成:

  {
StreamReader的SR =新的StreamReader(路径);
尝试
{
而(sr.Peek()> = 0)
Console.WriteLine(sr.ReadLine());
}
终于
{
如果(SR!= NULL)
sr.Dispose();
}
}



额外的花括号把限制的范围 SR ,所以它不是从使用块外访问。


Possible Duplicate:
What is the C# Using block and why should I use it?

So I've just noticed that at msdn examples and some stackoverflow questions there were answer where the using statement is used before the streamwriter etc, but what is actually the benefit? Since I've never been taught/told/read any reason to use it.

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

Instead of:

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

解决方案

The using block calls the Dispose method of the object used automatically, and the good point is that it is guaranteed to be called. So the object is disposed regardless of the fact an exception is thrown in the block of statements or not. It is compiled into:

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

The extra curly braces are put to limit the scope of sr, so that it is not accessible from outside of the using block.

这篇关于效益/使用前的StreamWriter,StreamReader的using语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆