尝试递增数组C#时出现Null引用异常

时间:2017-06-27 15:30:03

标签: c# arrays dictionary

尝试增加int []中的值时,我不断收到NullReferenceException。我尝试过多种方式初始化数组(计数),例如
int [] counts = {0,0};
int [] counts = new int [] {0,0};
int [] counts = new int [2] {0,0};
int [] counts = new int [2];
这些方法都没有给我一个不同的结果,见下面的代码:

 int[] counts = new int[2] {0, 0};
Console.WriteLine("Incrementing the warehouse dictionary at index: " + i);
//This will check and see if it's contained
if (warehouseCostsArray[i] != "")
{
    //This will check and see if it has the lowest price
    if (warehouseCostsArray[i] == "0")
    {
        //This will check and see if this brand already exists in the warehouse dictionary, it will return the counts if it is found
        if (dictionaryList[i].TryGetValue(lineContentsBrand, out counts))
        {
            Console.WriteLine("11\n");
            //incrememnt the counts based on the conditions
            counts[0]++;
            counts[1]++;
            //reassign that value in the dictionary
            dictionaryList[i][lineContentsBrand] = counts;

        }
        //same thing as above except this is triggered if that brand does not exist
        else
        {
            Console.WriteLine("22\n");
            counts[0] = 1;
            counts[1] = 1;
            dictionaryList[i].Add(lineContentsBrand, counts);

        }
    }
    //This is triggered if the warehouse contains the sku but does not have the lowest price.
    else
    {
        //same thing as above except this time we are not going increment counts[1]
        if (dictionaryList[i].TryGetValue(lineContentsBrand, out counts))
        {
            Console.WriteLine("33\n");
            counts[0]++;
            dictionaryList[i][lineContentsBrand] = counts;

        }
        else
        {
            Console.WriteLine("44\n");
            //This will add if it doesnt exist, leaving counts[1] as 0
            Console.WriteLine("Incrementing counts 0");
            counts[0] = 1;
            Console.WriteLine("Incrementing counts 1");
            counts[1] = 0;
            Console.WriteLine("Adding entry to the dictionary");
            dictionaryList[i].Add(lineContentsBrand, counts);

        }
    }
 }

尝试设置

时,错误发生在最后一个 else
counts[0]=1;

这是包含输出的图片 Console output

我知道这是一个经常被问到的问题,但我完全陷入困境,似乎无法克服这个问题。任何帮助表示赞赏!

谢谢, 本

0 个答案:

没有答案
相关问题