我有代码创建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
内声明的变量是否安全?