0

这是我的代码的一部分。

List<DateTime>[] newarraydate1 = new List<DateTime>[70];
DateTime temp1 = arraydate1[k][aa];
newarraydate1[k].Add(temp1);

我使用了 messagebox.show(temp1) 并且 temp1 中有一个值。错误显示在程序的第一行。

4

3 回答 3

2

创建数组时,只创建包含结构。它的成员被初始化为其默认值,在 is 的情况List<DateTime>null。从本质上讲,您会获得 70 份null参考资料,每份参考资料都可以保存一份DateTime.

要解决此问题,您应该在循环中分配新数组

List<DateTime>[] newarraydate1 = new List<DateTime>[70];
for (int i = 0 ; i != newarraydate1.Length ; i++) {
    newarraydate1[i] = new List<DateTime>();
}

或使用 LINQ:

List<DateTime>[] newarraydate1 = Enumerable
    .Range(0, 70)
    .Select(n => new List<DateTime>())
    .ToArray();
于 2013-05-04T15:10:17.880 回答
1

您正在声明一个数组,List<DateTime>但从未在该数组中创建 List 的任何实际实例。您需要以这种方式修改代码:

List<DateTime>[] newarraydate1 = new List<DateTime>[70];
for(int i=0;i<70;i++)
    newarraydate1[i]=new List<DateTime>();
DateTime temp1 = arraydate1[k][aa];
newarraydate1[k].Add(temp1);
于 2013-05-04T15:09:11.527 回答
0

如果您故意创建一个s列表数组,则必须首先在条目中创建每个列表DateTime

newarraydate1[k] = new List<DateTime>();

只有这样你Add才能进入k第一个列表(如你问题的最后一个代码行)。

于 2013-05-04T15:14:02.723 回答