很高興今天看到一個可以拿出來分享的知識點,那就是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!
好拉,今天的執筆就到此為止,謝謝大家!