C#裡using的作用——釋放資源

來源:互聯網
上載者:User

很高興今天看到一個可以拿出來分享的知識點,那就是using的使用。

其實關於using的作用,我想大家最多的用在引入命名空間。:)其實我在這之前也跟大家一樣,不過今天在看一個小例子後,則讓我產生了疑問。好拉,我先把代碼附上吧。

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

不知道上面的程式有沒有一處讓你比較困惑的呢,好拉,我就不賣關子了,我不懂的那一處如下:

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;</p><p>class Program<br />{<br /> public static void Main(string[] args)<br /> {<br /> using (Test test = new Test())<br /> {<br /> Console.WriteLine("Disposable is open!");<br /> }</p><p> Console.WriteLine("Disposable is none!");<br /> Console.ReadKey();<br /> }<br />}</p><p>public class Test:IDisposable<br />{</p><p> #region IDisposable 成員</p><p> public void Dispose()<br /> {<br /> Console.WriteLine("Disposable is close!");<br /> }</p><p> #endregion<br />}

這裡輸出的結果是:

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

好拉,今天的執筆就到此為止,謝謝大家!

聯繫我們

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