使用 object[] 将数据添加到数据表不起作用?

mez*_*hic 0 .net c# datatable

DataTable 的 Add 方法包含一个重载,用于使用对象数组将数据添加到表中。

我想要一个数组数组,我可以循环遍历它并将其插入到数据表中。下面的代码创建一个大小为 4000 的数组,并将一个包含 4 个“列”的数组放入外部数组 (ContigeousTradeMem) 的第 0 个元素中。

但是,当我调试 testObject 中(以及缓存中的 ContigeousTradeMem[])中所有数据下面的最后一行时,不会将其复制到 DataTable() 中???

//The "array" which we wish to insert into the DataTable
object[] testObject = new object[4];

//Inserts some test data
for (int m = 0; m < 4; m++)
{
    testObject[m] = "test";
}

//A test DataTable
DataTable test = new DataTable();
test.Columns.Add("Col1");
test.Columns.Add("Col2");
test.Columns.Add("Col3");
test.Columns.Add("Col4");

//Put the test "array" into the cache
ContiguousTradeMem[0] = testObject; //The data of testObject is fine here

//Write the cache element to the DataTable
test.Rows.Add(ContiguousTradeMem[0]); //The data is not fine in test.Rows
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 5

实际上,重载DatarowCollection.Add需要一个param类似于参数列表的数组。您可以通过以下方式初始化并添加数组中的 DataRow:

var row = test.NewRow();
row.ItemArray = (Object[])ContiguousTradeMem[0];
test.Rows.Add(row);
Run Code Online (Sandbox Code Playgroud)

参数 C#