using 语句和IDisposable接口

/*某些类型的非托管对象有数量的限制或很费系统资源。在使用完后,尽可能早的释放他们是非常重要的。

using语句有助于简化该过程并确保这些资源被适当的处置(dispose);

资源是指实现了system.IDisposable接口的类或者结构;Disposable接口含有单一的方法Dispose的方法;*/

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

namespace ConsoleApplication2

{

    class Program

    {

        static void Main(string[] args)

        {  //using 语句不同于上面的using指令

            using (TextWriter tw = File.CreateText("file.txt"))

            {

                tw.WriteLine("我在写文件");

            }

            //using 语句

            using (TextReader tr=File.OpenText("file.txt"))

            {

                string inputstring;

                while(null!=(inputstring=tr.ReadLine()))

                {

                    Console.WriteLine("文件的内容为:{0}",inputstring);

                }



            }

            Console.Read();

        }

    }

}

/*TextWriter和TextReader类都实现了IDisposable接口,这是using语句的要求

 * TextWriter资源打开一个文本文件,并向文件写入一行;

 * TextReader资源接着打开相同的文本文件,一行一行的读取并显示它的内容。

 * 在这种情况下,using语句要确保调用对象的Dispose方法。

 */

/*

 * using语句还可以用于相同类型的多个资源,资源声明之间用逗号隔开;

 * 括号里也可以写多个using (TextWriter tw_1 = File.CreateText("file_1.txt"),TextWriter tw_2 = File.CreateText("file_2.txt"))

 * */

 

你可能感兴趣的:(OS)