簡體   English   中英

我應該如何正確處置物體?

[英]How should I correctly dispose of an object?

我經常使用以下代碼(或類似代碼)來處理對象:

SqlCommand vCmd = null;

try 
{
    // CODE
}
catch(Exception ex) { /* EXCEPTION HANDLE */ }
finally 
{
    if (vCmd != null) 
    {
        vCmd.Dispose();
        vCmd = null;
    }
}

這是釋放對象和處置對象的最佳方法嗎?

我正在使用VS分析,並給我有關冗余的警告。 但是我總是這樣

就可讀性而言,最好的方法是使用using語句

using(SqlCommand vCmd = new SqlCommand("...", connection)
{
    try 
    {
        // CODE
    }
    catch(Exception ex) 
    { 
        // EXCEPTION HANDLE
    }
}

它即使在發生錯誤的情況下也可以放置對象,因此與finally相似。 當對象實現IDisposable表示對象使用非托管資源時,應始終使用它。

進一步閱讀:

這是來自MSDN的示例:

private static void ReadOrderData(string connectionString)
{
    string queryString = 
        "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

注意連接使用“ using”。

回到COM / ActiveX的過去,您需要將對象設置為“ Nothing”。

在托管代碼中,這不再是必需的。

您既不應調用“ Dispose()”,也不應將sqlCommand設置為“ null”。

只需停止使用它-並信任.Net垃圾收集器即可完成其余工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM