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':类型在using语句中使用必须可以隐式转换为'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
语句?