0

我想制作一些虚拟数据以在我的 asp.net mvc 3 视图中使用。以下代码是控制器的一部分,应该将数据传递给视图。

List<KeyValuePair<int, int>> dummyData = new List<KeyValuePair<int, int>>();
                dummyData.Add(new KeyValuePair<int, int>(1,1));
                dummyData.Add(new KeyValuePair<int, int>(1,2));
                dummyData.Add(new KeyValuePair<int, int>(2,1));
                dummyData.Add(new KeyValuePair<int, int>(3,1));
                dummyData.Add(new KeyValuePair<int, int>(4,1));
                dummyData.Add(new KeyValuePair<int, int>(4,2));
                dummyData.Add(new KeyValuePair<int, int>(4,3));
                dummyData.Add(new KeyValuePair<int, int>(4,4));

顾名思义,这是我的虚拟数据。这背后的想法是,第一个数字代表表格中的行号,第二个数字代表列号。我想以某种方式组合与同一行相关但具有不同列号的记录。为此,我选择使用二维数组:

int dummyCount = dummyData.Count;

            List<KeyValuePair<int, int>>[,] dummyArray = new List<KeyValuePair<int, int>>[dummyCount,dummyCount];

            int index1 = -1;
            int index2 = 0;

            for (int i = 0; i < dummyCount; i++)
            {

                int tempColNum = 1;
                if (dummyData[i].Value != tempColNum)
                {
                    dummyArray[index1, index2].Add(dummyData[i]);
                    index2++;
                }
                else
                {
                    index1++;
                    index2 = 0;
                    dummyArray[index1, index2].Add(new KeyValuePair<int, int>(dummyData[i].Key, dummyData[i].Value));
                }
            }

但是当我到达这里时:dummyArray[index1, index2].Add(new KeyValuePair<int, int>(dummyData[i].Key, dummyData[i].Value));我从标题中得到错误:Object reference not set to an instance of an object.。最初我只尝试过dummyArray[index1, index2].Add(dummyData[i]);,但得到了同样的错误。

4

3 回答 3

7

您的虚拟数组未初始化。所有单元格均为空。您需要在每个单元格中创建列表,如下所示:

if (dummyArray[index1, index2] == null) 
  dummyArray[index1, index2] = new List<KeyValuePair<int, int>>()

此外,您的代码可能会出现无效的索引引用。如果在第一个周期

if (dummyData[i].Value != tempColNum)

将评估为真,您将尝试从索引 [-1,0] 处的虚拟数组中提取元素

于 2013-04-23T09:35:03.267 回答
0

It seems like the both code fragments are not really connected. In the second fragment you create a new dummyArray which only creates the list but not the elements. And you start using the elements in the remainder of the second fragment.

You should add the elements like fragement one between the creation of the list and the usage.

于 2013-04-23T09:37:05.387 回答
0

因为当你调用dummyArray[index1, index2].Add(new KeyValuePair<int, int>(dummyData[i].Key, dummyData[i].Value));虚拟数组元素时仍然没有初始化。

您应该检查 null 如下代码:

if (dummyArray[index1, index2] == null)
{
     dummyArray[index1, index2] = new List<KeyValuePair<int, int>>();
}

希望这有帮助。

于 2013-04-23T09:41:17.387 回答