【发布时间】:2010-02-22 18:37:36
【问题描述】:
我正在查看 ASP.NET 应用程序中的一些旧 C#.NET 代码,以确保所有 SqlConnections 都包装在 using 块中。
我知道 using 与 try / finally 相同,它在 finally 中处理对象> 不管try中发生了什么。如果我有一个在 using 中返回值的方法,即使执行在返回时离开该方法,它是否仍然在我的对象上调用 .Dispose()/在它返回期间/之后?
public static SqlCommand getSqlCommand(string strSql, string strConnect){
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
SqlCommand cmd = GetSqlCommand();
cmd.Connection = con;
cmd.CommandText = strSql;
return cmd;
}
}
更新: 接受的答案是我认为最能回答我的问题的答案,但请注意 this answer 发现了这段代码的愚蠢之处,即我正在返回一个使用已处置连接的命令! :P
【问题讨论】:
标签: c# .net idisposable