昨天的“【windows phone】simple note”中的代碼中有一個using的用法,剛開始查看了一些資料說是強制關閉對象的一個命令。今天又查了一些資料,才明白,原來using指令調用了一個方法——Dispose()方法。而Dispose()方法的作用就是釋放所有的使用資源。
例:
public void ExecuteCommand( string connString, string commandString )
{
SqlConnection myConnection = new SqlConnection( connString );
SqlCommand mySqlCommand = new SqlCommand( commandString,
myConnection );
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
}
這個例子中的兩個可處理對象沒有被恰當的釋放:SqlConnection和SqlCommand。兩個對象同時保存在內存里直到析構函數被調用。
解決這個問題的方法就是在使用完命令和鏈接后就調用它們的Dispose:
public void ExecuteCommand( string connString, string commandString )
{
SqlConnection myConnection = new SqlConnection( connString );
SqlCommand mySqlCommand = new SqlCommand( commandString,
myConnection );
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
mySqlCommand.Dispose( );
myConnection.Dispose( );
}
使用using語句也可以很好的實現此功能,而且代碼很清晰:
public void ExecuteCommand( string connString, string commandString )
{
using ( SqlConnection myConnection = new SqlConnection( connString ))
{
using ( SqlCommand mySqlCommand = new SqlCommand( commandString, myConnection ))
{
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
}
}
}
當你在一個函數內使用一個可處理對象時,using語句是最簡單的方法來保證這個對象被恰當的處理掉。當這些對象被分配時,會被編譯器放到一個try/finally塊中。
SqlConnection myConnection = null;
// Example Using clause:
using ( myConnection = new SqlConnection( connString ))
{
myConnection.Open();
}
// example Try / Catch block:
try {
myConnection = new SqlConnection( connString );
myConnection.Open();
}
finally {
myConnection.Dispose( );
}
有時候使用try/finally塊的時候會發現如果發生錯誤,程序不會報錯。本人感覺還是使用using語句比較好。