c#遍历二维List出错

来源:百度知道 编辑:UC知道 时间:2024/09/23 12:10:42
using System;
using System.Collections.Generic;
using System.Text;

namespace Cast
{
class Program
{
static void Main(string[] args)
{
List<int> listTemp = new List<int>();
List<List<int>> D2List = new List<List<int>>();

for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
D2List[i].Add(i * j);
}
}

for (int m = 0; m < 9; m++)
{
for (int n = 0; n < 9; n++)
{
Console.Write(D2List[m][n].ToString());
}
}
System.Threading.Thread.Sleep(1000);
}
}
}

代码可直接复制

出错为Index was out of range. M

你认真学习下实例,然后看下listTemp.Clear(); 你都把listTemp清空了,之前添加的也都清空了,所以根本就没有D2List里面根本就没有东西,把List<int> listTemp = new List<int>(); 写到for循环的第一个括号里面就好了

为什么不这么定义呢:
List<int>[] listTemp = new List<int>(10);