我有以下代码.
private DataTable LoadSMSCellProviders() { string sqlQuery = "Select * from SMSAddress"; DataTable dt = new DataTable(); using (sqlConnection conn = new sqlConnection(Utility.ConnString)) { using (sqlCommand command = new sqlCommand(sqlQuery,conn)) { sqlDataAdapter adapter = new sqlDataAdapter(command); adapter.Fill(dt); return dt; } } }
Microsoft Code Analysis告诉我dt没有沿所有执行路径处理,但我不知道如何纠正这个问题.如果我在返回之前尝试调用dispose,它将返回一个null值,如果我尝试在方法结束时执行它,则代码永远不会到达…
我在这里错过了什么?
这是来自分析工具的消息:
warning : CA2000 : Microsoft.Reliability : In method ‘x.x()’,object
‘dt’ is not disposed along all exception paths. Call
System.IDisposable.Dispose on object ‘dt’ before all references to it
are out of scope.
@R_403_323@
发生异常时需要处理它.像这样.
private DataTable LoadSMSCellProviders() { string sqlQuery = "Select * from SMSAddress"; DataTable dt = null; try { dt = new DataTable(); using (sqlConnection conn = new sqlConnection(Utility.ConnString)) { using (sqlCommand command = new sqlCommand(sqlQuery,conn)) { sqlDataAdapter adapter = new sqlDataAdapter(command); adapter.Fill(dt); return dt; } } } catch { if(dt != null) dt.Dispose(); throw; } }