有两种方法来分配一个二维数组
方法1:
在这里,您使用空字符串进行初始化
string[,] columnsAndTheirNames1 = new string[2, 3];
方法2:
在这里,您使用字符串字面量进行了初始化。
string[,] columnsAndTheirNames = {
{ "row1-col1", "row1-col2"},
{ "row2-col1", "row2-col2"},
{ "row3-col1", "row3-col2"}
};
在这里,您可以看到如何访问它:
for (int i = 0; i < columnsAndTheirNames.GetLength(0); ++i) {
for (int j = 0; j < columnsAndTheirNames.GetLength(1); ++j) {
Console.Write(columnsAndTheirNames[i, j] + "\t");
}
Console.WriteLine();
}
输出将如下所示
row1-col1 row1-col2
row2-col1 row2-col2
row3-col1 row3-col2
所以你的代码应该像下面这样:
string[] thisCanVaryInLength = new string[3] { "col1,nam1", "col2,nam2", "col3,nam3" };
string[,] columnsAndTheirNames = new string[2, thisCanVaryInLength.Length];
for (int i = 0; i < thisCanVaryInLength.Length; i++) {
var items = thisCanVaryInLength[i].Split(',');
columnsAndTheirNames[0, i] = items[0];
columnsAndTheirNames[1, i] = items[1];
}
for (int i = 0; i < columnsAndTheirNames.GetLength(0); ++i) {
for (int j = 0; j < columnsAndTheirNames.GetLength(1); ++j) {
Console.Write(columnsAndTheirNames[i, j] + "\t");
}
Console.WriteLine();
}
而且输出是
col1 col2 col3
nam1 nam2 nam3