当我想将项目添加到锯齿状数组中的元素时,我收到 NullReferenceException。
public List<int>[][] Map;
void Start()
{
Map = new List<int>[60][];
for(byte x = 0; x < 60 ; x++)
{
Map[x] = new List<int>[60];
// initialization of rows
}
Map [23] [34].Add (21);
}
最佳答案
你有一个锯齿状数组,它的每个元素都是 List<int>
。您初始化数组,但不初始化元素。
所以当你调用Add
时在未初始化的元素上,即 List<int>
你得到了异常(exception)。
Map = new List<int>[60][];
for (int x = 0; x < 60; x++)
{
Map[x] = new List<int>[60];
for (int y = 0; y < 60; y++)
{
Map[x][y] = new List<int>(); // initializing elements
}
// initialization of rows
}
Map[23][34].Add(21);
关于c# - 通过 for 循环初始化带有 Lists<int> 的交错数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37054008/