C#里using的妙用(释放资源)

来源:互联网 发布:怎么添加网络打印机xp 编辑:程序博客网 时间:2024/06/08 16:56

       其实关于using的作用,我想大家最多的用在引入命名空间。其实我在这之前也跟大家一样,不过今天在看一个小例子后,则让我产生了疑问。好拉,我先把代码附上吧。

using System;using System.IO;class Test {    public static void Main()     {        try         {            // Create an instance of StreamReader to read from a file.            // The using statement also closes the StreamReader.            using (StreamReader sr = new StreamReader("TestFile.txt"))             {                string line;                // Read and display lines from the file until the end of                 // the file is reached.                while ((line = sr.ReadLine()) != null)                 {                    Console.WriteLine(line);                }            }        }        catch (Exception e)         {            // Let the user know what went wrong.            Console.WriteLine("The file could not be read:");            Console.WriteLine(e.Message);        }    }}

不知道上面的程序有没有一处让你比较困惑的呢,好拉,我就不卖关子了,我不懂的那一处如下:


using (StreamReader sr = new StreamReader("TestFile.txt"))

{

       .....................


        一开始我以为是引入命名空间什么的,不过带着怀疑的态度,我到Q群里提出我自己的疑问。好在在他们的帮助下,让我纠正了我之前的错误想法。其实我们在连接数据库的时候也经常会使用到using的语法,类似下面这句:


using (SqlConnection conn = new SqlConnection(source))
{
       //code
}


千万不要以为任何地方的实例化都可以这样使用在using块里的哦,一般是在需要自动释放资源的地方才会用到。其实说需要自动释放资源,可能大家也不是很理解。这样说吧,你想要能这样使用using块的话,你需要保证满足下面一点:


(1)此类实现了接口IDisposable(这个接口只有一个方法void Dispose()),当这个类在using中实例化的时候,using代码块结束时会自动调用这个类中实现了接口IDisposable的Dispose()方法。Dispose()方法中常用来做些释放资源的动作


看看下面的一个简单的例子:


using System;class Program{    public static void Main(string[] args)    {        using (Test test = new Test())        {            Console.WriteLine("Disposable is open!");        }        Console.WriteLine("Disposable is none!");        Console.ReadKey();    }}public class Test:IDisposable{    #region IDisposable 成员    public void Dispose()    {        Console.WriteLine("Disposable is close!");    }    #endregion}

这里输出的结果是:

Disposable is open!
Disposable is close!
Disposable is none!

好拉,今天的执笔就到此为止,谢谢大家!


注:ADO.net 中的连接等操作都实现了IDisposable接口,可以使用using进行资源管理!

 using (SqlConnection conn = new SqlConnection(@"Data Source=(localDB)\V11.0;        AttachDbFilename=E:\HUST-CODE\ADO_NETPra\ADO_NETPra\Database1.mdf;Integrated Security=True"))            {                conn.Open();                using (SqlCommand cmd=conn.CreateCommand())                {                    cmd.CommandText ="insert into Book(Name) values('charles')";                    cmd.ExecuteNonQuery();                    Console.WriteLine("执行成功!");                }            }



0 0
原创粉丝点击