在函式內使用可處理物件時,using 陳述式是確保物件妥善處理的最簡單方法。物件配置時,編譯器將其置入 try/finally 區塊。下列兩段程式碼編譯成相同 IL:
SqlConnection myConnection = null;
// Example Using clause:
using (myConnection = new SqlConnection(connString)) { myConnection.Open(); }
// example Try / Finally block:
try { myConnection = new SqlConnection(connString); myConnection.Open(); }
finally { myConnection.Dispose(); }
(譯註:個人經驗覺得這樣做很不方便。可保證資源釋放,卻無法發現錯誤。關於同時拋出例外又釋放資源的方法,可參考 Jeffrey 的《.NET 框架程式設計》修訂版。)
若將不支援處理的型別變數置於 using 內,編譯器報錯:
// Does not compile: String is sealed, does not support IDisposable.
using (string msg = "This is a message") Console.WriteLine(msg);
// Does not compile: Object does not support IDisposable.
using (object obj = Factory.CreateResource()) Console.WriteLine(obj.ToString());
using 僅能在編譯時期用於支援 IDisposable 的型別。若 obj 實作 IDisposable,產生清理程式碼;否則退化為 using(null),安全但無作用。不確定物件是否應置於 using 時,寧可為安全著想:假設要處理,按前述方法置入 using。
前例需釋放連線與命令兩物件。建立兩個 using 陳述式,每個包含一可處理物件,等效於:
public void ExecuteCommand(string connString, string commandString)
{
SqlConnection myConnection = null;
SqlCommand MySQLCommand = null;
try {
myConnection = new SqlConnection(connString);
try {
MySQLCommand = new SqlCommand(commandString, myConnection);
myConnection.Open();
MySQLCommand.ExecuteNonQuery();
} finally {
if (MySQLCommand != null) MySQLCommand.Dispose();
}
} finally {
if (myConnection != null) myConnection.Dispose();
}
}