![](/img/trans.png)
[英]How to fix a CA2000 IDisposable C# compiler warning, when using a global cache
[英]How to fix this CA2000 for SqlCommand?
我正在嘗試執行如下所示的SQL查詢,但是Visual Studio抱怨CA2000。
public static IDictionary<string, string> TemplateDirectories(string connectionString) {
var directories = new Dictionary<string, string>();
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
using (var command = new SqlCommand { Connection = connection, CommandText = "select * from PATHS" }) {
var reader = command.ExecuteReader();
while (reader.Read())
directories[reader["CODE"].ToString()] = reader["PATH"].ToString();
reader.Close();
}
}
return directories;
}
錯誤CA2000 ...對象'new SqlCommand()'並未沿所有異常路徑放置。 在對對象'new SqlCommand()'的所有引用超出范圍之前,請調用System.IDisposable.Dispose。
我嘗試了幾種方法來修復它,但沒有人起作用。 那么如何解決?
嘗試顯式分配command
參數:
using (var command = new SqlCommand())
{
command.Connection = connection;
command.CommandText="select * from PATHS";
var reader = command.ExecuteReader();
while (reader.Read())
directories[reader["CODE"].ToString()] = reader["PATH"].ToString();
reader.Close();
}
這是由於使用對象初始化程序時存在陷阱。
初始化SqlCommand
的方式,如果在初始化對象時發生某些異常,則將不處理SqlCommand
。
那么解決方案是什么。 以老式的方式聲明對象,以擺脫警告-
using (var command = new SqlCommand())
{
command.Connection = connection;
command.CommandText="select * from PATHS";
...
}
我找到了一篇很好的文章,其中提供了更多詳細信息和解決此問題的方法-http://haacked.com/archive/2013/01/11/hidden-pitfalls-with-object-initializers.aspx/
話雖如此,對於這個棘手的問題,最好使用SqlCommand
構造函數並像這樣傳遞命令文本和連接對象( 由Damien_The_Unbeliever提供 )
string commandText = "select * from PATHS";
using (var command = new SqlCommand(commandText, connection))
{
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.