处置或不处理(CA2000)

Han*_*ing 13 .net dispose code-analysis

我正在开启旧项目的代码分析.大多数评论结果我都能理解,但 CA2000:在丢失范围之前处理对象很难做到.

例如,来自ASP.Net页面的此代码:

private void BuildTable()
{
    HtmlTableRow tr = new HtmlTableRow();
    HtmlTableCell td = new HtmlTableCell();

    tr.Cells.Add(td);
    // add some controls to 'td'

    theTable.Rows.Insert(0, tr);
    // 'theTable' is an HtmlTable control on the page
}
Run Code Online (Sandbox Code Playgroud)

提供CA消息:

CA2000:Microsoft.Reliability:在方法'BuildTable()'中,在对所有引用超出范围之前,在对象'tr'上调用System.IDisposable.Dispose.

CA2000:Microsoft.Reliability:在方法'BuildTable()'中,对象'td'未沿所有异常路径放置.在对对象'td'的所有引用都超出范围之前调用System.IDisposable.Dispose.(以及关于添加到'td'的控件的类似消息.)

我可以解决第二个问题:

private void BuildTable()
{
    HtmlTableRow tr = new HtmlTableRow();
    HtmlTableCell td = new HtmlTableCell();

    try
    {
        tr.Cells.Add(td);
        // add some controls to 'td'

        td = null; // this line is only reached when there were no exceptions
    }
    finally
    {
        // only dispose if there were problems ('exception path')
        if (td != null) td.Dispose();
    }

    theTable.Rows.Insert(0, tr);
}
Run Code Online (Sandbox Code Playgroud)

但我不认为有可能解决有关'tr'的消息.我无法处理,因为在方法退出后仍然需要它.

还是我错过了什么?

顺便说一句:改变该theTable.Rows.Insert进入theTable.Rows.Add变化CA消息"沿着所有不设置异常路径"

Mar*_*age 10

代码分析无法完全理解您的代码,只是警告您是否创建了似乎没有处置的一次性对象.在您的情况下,您应该关闭警告,因为在离开方法之前不应该丢弃对象.您可以通过自定义代码分析规则集或在具有此警告的每个方法上显示代码分析错误,从而关闭整个项目的警告.

也就是说,我建议你using在处理IDisposable对象时使用构造:

using (var tr = new HtmlTableRow()) {
  using (var td = new HtmlTableCell()) {
    tr.Cells.Add(td);
    theTable.Rows.Insert(0, tr);
  }
}
Run Code Online (Sandbox Code Playgroud)

除了这个代码是无稽之谈,因为你不想处理你刚刚添加到表中的行和单元格.