簡體   English   中英

用列表初始化鋸齒狀數組<int>在 for 循環里面

[英]Initializing jagged arrays with Lists<int> inside by a for loop

當我想將項目添加到鋸齒狀數組中的元素時,我得到 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> 您初始化數組而不是元素。

因此,當您對List<int>的未初始化元素調用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM