很多SO的人指出我應該更頻繁地使用using
聲明。所以我在練習。當使用語句應該使用?
問題是我無法決定何時使用它以及何時不使用它。當我想我應該用它,然後我得到的錯誤,如在這個例子中(PS HashPhrase是我創建的類):
using (HashPhrase hash = new HashPhrase())
{
connection.ConnectionString =
"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + filePath + ";" +
"Persist Security Info=False;" +
"Jet OLEDB:Database Password=" + hash.ShortHash(pass) + ";";
}
但它給我一個錯誤:'Password_Manager.HashPhrase': type used in a using statement must be implicitly convertible to 'System.IDisposable'
但在這個例子正常工作:
using (OleDbConnection connection = new OleDbConnection())
{
connection.ConnectionString =
"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + filePath + ";" +
"Persist Security Info=False;" +
"Jet OLEDB:Database Password=" + hash.ShortHash(pass) + ";";
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
是否有任何快速指南如何確定何時使用using
聲明?
這很有道理。 – HelpNeeder
@downvoter:你願意解釋一下downvote的原因嗎? – LukeH