加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 对象未沿所有执行路径布置

发布时间:2020-12-15 08:23:44 所属栏目:百科 来源:网络整理
导读:我有以下代码. private DataTable LoadSMSCellProviders(){ string sqlQuery = "Select * from SMSAddress"; DataTable dt = new DataTable(); using (SqlConnection conn = new SqlConnection(Utility.ConnString)) { using (SqlCommand command = new SqlC
我有以下代码.
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.

解决方法

发生异常时需要处理它.像这样.
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;
    }
}

这个想法是,如果发生异常,那么就无法处理DataTable,因为它不会被传递回调用者.因此,这是使代码分析愉快的模式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读