浅析using代码块的使用

  在浏览一些质量比较好的代码的时候会发现,涉及到连接操作和关闭连接操作的时候许多程序员都选用了using代码块。

  using代码块到底有什么作用呢,下面通过具体的例子来看看。

  (1)文本文件的读操作

 1 public string ReadText()
 2         {
 3 
 4             string path = @"C:\Users\Administrator\Desktop\ThisIsATxt.txt";
 5 
 6             using (StreamReader reader = new StreamReader(path, Encoding.UTF8))
 7             {
 8 
 9                 string Read_text = reader.ReadToEnd();
10 
11                 return Read_text;
12             }
13 
14         }

 

  (2)数据库操作类

 1 public class DetialDC
 2     {
 3         string connectionString = "Data Source=PC-20160624XQSU;Initial Catalog=Animal;Integrated Security=True";
 4 
 5         SqlConnection conn;
 6 
 7         #region 数据库查询操作
 8 
 9         public DataTable doSelect()
10         {
11 
12             string sql = "select * from detial";
13 
14             using (conn = new SqlConnection(connectionString))
15             {
16 
17                 conn.Open();
18 
19                 SqlDataAdapter da = new SqlDataAdapter(sql, conn);
20 
21                 DataSet ds = new DataSet();
22 
23                 da.Fill(ds);
24 
25                 return ds.Tables[0];
26 
27             }
28         }
29 
30         #endregion
31 
32     }

  从上面两个例子可以发现,最后需要被关闭的流和数据库连接,其实例化的操作都放在了using中。

  原理就是在using语句块执行完毕之后会调用using对象的IDisposable接口的Dispose()方法。

  即使using代码块中的语句抛出异常,Dispose()方法依然会被调用,从而确保无论如何,只要离开该段语句块就一定能够释放资源。

  using代码块为编程带来了方便,避免了忘记关闭连接而带来的种种麻烦,所以也可以将using代码块称为一个“语法糖”。

posted @ 2016-07-27 10:58  天青涩,再等你~  阅读(1005)  评论(0)    收藏  举报