我在对一个旧项目开启代码分析功能。大多数结果我都能理解,但是CA2000: 在作用域失效前释放对象很难做到正确。
例如,下面这段来自ASP.Net页面的代码:
例如,下面这段来自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
}
提供 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);
}
但我不认为有可能解决关于“tr”的消息。 我无法处理它,因为在方法退出后仍然需要它。
或者是我错过了什么?
顺便说一下:将theTable.Rows.Insert
更改为theTable.Rows.Add
会将CA消息更改为“在所有异常路径上未被处理”
<td>
的控件。 - Hans Kesting