C#3.0學習筆記(1)using語句和資源的封裝

來源:互聯網
上載者:User

一,  什麼叫資源?

資源就是一個實現了System.IDisposable介面的類或結構。

二,  using語句的作用?

Using語句協助減少意外的執行階段錯誤帶來的潛在問題,它整潔地封裝了資源的使用。

三,  using語句的使用形式?

Using(ResourceType Identifier=Expression)

{

      Statement;

}

註:1、圓括弧內的代碼分配資源。

      2、Statement語句使用資源。

四,using語句的實現原理?

       隱式調用try…finally…例外處理常式,它將Statement語句放進try塊中,將  Dispose方法放在finally塊中,以便及時釋放資源。

五,  using語句的使用樣本?

       代碼如下:

       class Program

    {

        static voidMain(string[] args)

        {

            string path = @"using.txt"; //最好將表示路徑的字串聲明為全域變量,這樣就可以重復調用.

            if (!File.Exists(path)) //判斷該檔案是否存在,如果不存在則創建檔案並寫入字元,如果則存則不執行塊中的代碼.

            {

                using (TextWriter tw = File.CreateText(path))

                {

                    tw.WriteLine("using語句樣本!");

                }

            }

           

            using (TextReader tr = File.OpenText(path))

            {

                string InputString;

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

                {

                    Console.WriteLine(InputString);

                    Console.ReadKey();

                }

            }

        }

    }

輸出結果為:

using語句樣本!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.