做一個測試,這樣一個類,繼承IDisposable,當Dispose方法被調用時,輸出id欄位:
class a : IDisposable
{
int id;
public a(int i)
{
id = i;
}
void IDisposable.Dispose()
{
Console.WriteLine(id);
}
}
然後:
using (new a(1))
using (new a(2))
using (new a(3))
{ }
事實上還可以這樣寫
using (a oa = new a(1), ob = new a(2), oc = new a(3))
{ }
不論上面哪種寫法,輸出都是:
3
2
1
可以看出來,最後定義的對象會被最先釋放!
這個在某些時候很有用的,比如多個對象互相有依賴關係,如果不用嵌套using的話:
//MemoryStream在System.IO;
//CryptoStream在System.Security.Cryptography;
ICryptoTransform trans;
/* 省略 */
//MemoryStream必須定義在前面,因為後面的CryptoStream需要它
var ms = new MemoryStream();
var cs = new CryptoStream(ms, trans, CryptoStreamMode.Read);
/* 省略 */
cs.Close();
//MemoryStream.Close必須在後面,因為CryptoStream的Close方法可能會往MemoryStream中
//再次寫入資料,因此MemoryStream必須在CryptoStream結束後再結束
ms.Close();
用using的話,看著就舒服多了!
ICryptoTransform trans;
/* 省略 */
using (var ms = new MemoryStream())
using (var cs = new CryptoStream(ms, trans, CryptoStreamMode.Read))
{
/* 省略 */
}