【问题标题】:Initializing jagged arrays with Lists<int> inside by a for loop通过 for 循环在内部使用 Lists<int> 初始化锯齿状数组
【发布时间】:2016-08-31 10:37:29
【问题描述】:

当我想将项目添加到锯齿状数组中的元素时,我得到 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);
}

【问题讨论】:

  • 在您开始向列表添加项目之前,您需要实例化您的列表。 IE。 Map[23][34] = new List&lt;Int&gt;()

标签: c# .net list jagged-arrays


【解决方案1】:

你有一个锯齿状数组,它的每个元素都是一个List&lt;int&gt;。您初始化数组而不是元素。

因此,当您在 List&lt;int&gt; 的未初始化元素上调用 Add 时,您会遇到异常。

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);

【讨论】:

  • 嗯,谢谢你的回答。需要澄清的一个问题:例如,当我制作 int 数组时,里面的 int 会立即初始化,但是在 List 数组中,Lists 不是?
  • 这是因为 int 是值类型,而 List&lt;T&gt; 是引用类型。当值类型被初始化时,它们会得到一个值。例如 int 变为 0 并且 bool 变为 false 但引用类型的默认值为 null。因此,当您尝试访问它们时,您会得到 NullReferenceException。
  • 啊该死的,非常感谢。我一直在阅读有关值/引用类型的内容,现在这些信息终于开始联系起来了。
猜你喜欢
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 2010-11-09
相关资源
最近更新 更多