我试过的代码如下:
private static List<List<List<int>>> threeDArrayToThreeDList(int [,,] letters) {
// 3d-array to 3d-list
List<List<List<int>>> letterslist = new List<List<List<int>>>();
List<List<int>> sublist = new List<List<int>> ();
List<int> subsublist = new List<int> ();
for (int i = 0; i < 2; i++) {
letterslist.Add (sublist);
for (int j = 0; j < 2; j++) {
letterslist[i].Add (subsublist);
for (int k = 0; k < 2; k++) {
Console.WriteLine (letterslist [i][j][k]); // Element not found
Console.WriteLine (letters [i,j,k]);
letterslist [i] [j] [k] = letters [i,j,k];
}
}
}
return letterslist;
}
为什么没有找到letterslist [i][j][k] ?
你的代码是错误的。您需要为每个"索引"创建一个列表。你的代码总共只创建了3个列表。
它应该是这样工作的:
private static List<List<List<int>>> threeDArrayToThreeDList(int [,,] letters) {
// 3d-array to 3d-list
List<List<List<int>>> letterslist = new List<List<List<int>>>();
for (int i = 0; i < 2; i++) {
letterslist.Add (new List<List<int>> ());
for (int j = 0; j < 2; j++) {
letterslist[i].Add (new List<int> ());
for (int k = 0; k < 2; k++) {
Console.WriteLine (letters [i,j,k]);
letterslist [i] [j].Add(letters [i,j,k]);
}
}
}
return letterslist;
}
这是因为letterslist [i][j]列表中没有元素。向它添加一个元素,它将带您通过导致异常的行。
将最内层循环中的代码修改如下:
for (int k = 0; k < 2; k++) {
letterslist[i][j].Add (letters[i, j, k]);
Console.WriteLine(letterslist[i][j][k]); // Should work fine
Console.WriteLine(letters[i, j, k]);
}