using關鍵字的用法以及作用

來源:互聯網
上載者:User
     其實對於.NET的學習者一開始都接觸using這個關鍵字了,可能大家沒有怎麼在意,包括我本人也是的,直到今天有人問我using的作用時,才引起了我的注意。
      概況來說可以分為兩種:第一種,就是using作為引用命名空間的引用(這個就是調用.NET的API或自己定義的方法),這一種其實比較常見我在這裡就不多說了。主要是第二種,先看一小Demo吧!

Code
 1using System;
 2using System.IO;
 3
 4/**//// <summary>
 5/// FileDemo 的摘要說明
 6/// </summary>
 7public class FileDemo
 8{
 9    public FileDemo()
10    {
11        //
12        // TODO: 在此處添加建構函式邏輯
13        //
14    }
15    public void MainMethodOne()  //這個是using的用法 隱式的調用Dispose()方法的
16    {
17        //建立寫入臨時檔案的字串
18        Byte[] bytesToWrite = new Byte[] { 1, 2, 3, 4, 5 };
19        //建立臨時檔案
20        using (FileStream fs = new FileStream("Temp.txt", FileMode.Create))
21        {
22            //將字串寫入臨時檔案
23            fs.Write(bytesToWrite, 0, bytesToWrite.Length);
24        }
25        //刪除臨時檔案
26        File.Delete("Temp.txt"); //現在它總能釋放資源
27    }
28
29    public void MainMethodTwo() //這個是顯示的調用Dispose()方法的
30    {
31        //建立寫入臨時檔案的字串
32        Byte[] bytesToWrite = new Byte[] { 1, 2, 3, 4, 5 };
33        //建立臨時檔案
34        FileStream fs = null;
35        try
36        { 
37            fs = new FileStream("Temp.txt", FileMode.Create));
38            //將字串寫入臨時檔案
39            fs.Write(bytesToWrite, 0, bytesToWrite.Length);
40        }
41        finally
42        {
43            //寫完後顯式關閉檔案
44            if(fs!=null)
45            {
46                (IDisposable)fs.Dispose();
47            }
48        }
49        //刪除臨時檔案
50        File.Delete("Temp.txt"); 
51    }
52}
53

在這裡using的作用是作為一個臨時對象的生存地區;因為.NET是Managed 程式碼的機制,而我們有時需要代碼要求非託管資源,如檔案控制代碼或SQL串連。在使用一個或多個此類資源完成代碼後,using塊確保這些資源的釋放。在這種情況下我們就需要使用using了。
using 塊可以分擷取、使用和釋放三個部分。
1.擷取表示建立變數並將其初始化,以便引用系統資源。在using()中
2.使用表示訪問資源並使用資源執行操作。using{}之間的語句代表資源的使用過程。
3.釋放表示針對resourcename中的對象調用Dispose方法。這使該對象可以完全終止其非託管資源“}”塊釋放“{”塊控制的資源。
基本上就是這些了吧!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.