我有以下带有三个 CA2000 警告的代码。对于 cellFirst 变量,我可以通过使用“使用”块来克服这个问题。但是对于其他两个 headercells,控件是在辅助函数中创建的。
CA2000:Microsoft.Reliability:在方法 GetTableCell(string, int, string, string) 中,对象“lnkHide”并未沿所有异常路径进行处理。在对对象“lnkHide”的所有引用超出范围之前调用 System.IDisposable.Dispose。
CA2000:Microsoft.Reliability:在方法 GetTableCell(string, int, string, string) 中,对象“ltlText”并未沿所有异常路径进行处理。在对对象“ltlText”的所有引用超出范围之前调用 System.IDisposable.Dispose。
CA2000:Microsoft.Reliability:在方法 GetTableCell(string, int, string, string) 中,对象“newCell”并未沿所有异常路径进行处理。在对对象“newCell”的所有引用超出范围之前调用 System.IDisposable.Dispose。
代码
protected void grdTransactions_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e != null)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow newHeaderRow = null;
try
{
newHeaderRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
using (TableHeaderCell cellFirst = new TableHeaderCell())
{
cellFirst.ColumnSpan = 1;
cellFirst.Text = "FIRST";
newHeaderRow.Cells.Add(cellFirst);
}
//Associate
#region Associate
TableHeaderCell cellAssociate = GetTableCell("tableColGroupAssociate", 4, "associateHide", "Associate Transaction Info");
#endregion
//Financial
#region Financial
TableHeaderCell cellFinancial = GetTableCell("tableColGroupTransaction", 5, "financialHide", "Financial Transaction Info");
#endregion
newHeaderRow.Cells.Add(cellAssociate);
newHeaderRow.Cells.Add(cellFinancial);
((GridView)sender).Controls[0].Controls.AddAt(0, newHeaderRow);
}
finally
{
if (newHeaderRow != null)
{
newHeaderRow.Dispose();
newHeaderRow = null;
}
}
}
}
}
private static TableHeaderCell GetTableCell(string cssClassName, int colSpan, string hideClassName, string displayName)
{
TableHeaderCell newCell = new TableHeaderCell();
newCell.ColumnSpan = colSpan;
newCell.CssClass = cssClassName;
LiteralControl ltlText = new LiteralControl();
ltlText.Text = displayName;
newCell.Controls.Add(ltlText);
HyperLink lnkHide = new HyperLink();
lnkHide.Text = SupportToolUIResource.HideLinkText;
lnkHide.CssClass = hideClassName;
lnkHide.Target = SupportToolUIResource.HideLinkTarget;
newCell.Controls.Add(lnkHide);
return newCell;
}
参考:
更新代码
使用块来克服警告
using (TableHeaderCell cellAssociate = new TableHeaderCell())
{
GetTableCell(cellAssociate,"tableColGroupAssociate", 4, "associateHide", "Associate Transaction Info");
newHeaderRow.Cells.Add(cellAssociate);
}
private static void GetTableCell(TableHeaderCell cellAssociate, string cssClassName, int colSpan, string hideClassName, string displayName)
{
cellAssociate.ColumnSpan = colSpan;
cellAssociate.CssClass = cssClassName;
using (LiteralControl ltlText = new LiteralControl())
{
ltlText.Text = displayName;
cellAssociate.Controls.Add(ltlText);
}
using (HyperLink lnkHide = new HyperLink())
{
lnkHide.Text = SupportToolUIResource.HideLinkText;
lnkHide.CssClass = hideClassName;
lnkHide.Target = SupportToolUIResource.HideLinkTarget;
cellAssociate.Controls.Add(lnkHide);
}
}
问题
应用程序“使用”块(如更新的代码所示)中是否有任何陷阱来克服警告?