CA2000:在DataTable上丢失范围之前处置对象 - 需要解释

时间:2015-09-16 12:09:24

标签: c# .net code-analysis

我有代码创建DataTable并返回它,如下所示:

public static DataTable Transpose(DataTable input)
{
    DataTable transpose = new DataTable();

    // first column name remains unchanged
    transpose.Columns.Add(input.Columns[0].ColumnName); 

    for (int i = 1; i < input.Columns.Count; i++)
    {
        // all other column names become first row
        transpose.Rows.Add(new object[] { input.Columns[i].ColumnName }); 
    }

    for (int j = 0; j < input.Rows.Count; j++)
    {
        // all row values in column 0 are now column names
        transpose.Columns.Add(input.Rows[j][0].ToString()); 

        for (int i = 1; i < input.Columns.Count; i++)
        {
            transpose.Rows[i - 1][j + 1] = input.Rows[j][i].ToString();
        }
    }

    return transpose;
}

我在代码分析中收到此警告:CA2000: Dispose objects before losing scope

当然,使用using

可以轻松修复警告
public static DataTable Transpose(DataTable input)
{
    using(DataTable transpose = new DataTable())
    {
        // same stuff here

        return transpose;
    }
}

但为什么?
(a)为什么原始代码抛出警告?
(b)从using内的 块中返回using内声明的变量是否安全?

0 个答案:

没有答案