首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Effective C# 原則 15:使用 using 與 try/finally 進行資源清理(二)

     編輯:關於C語言

using 陳述式的編譯行為

在函式內使用可處理物件時,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();
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved