这是我的代码的一部分。c#:未将对象引用设置为对象的实例
List<DateTime>[] newarraydate1 = new List<DateTime>[70];
DateTime temp1 = arraydate1[k][aa];
newarraydate1[k].Add(temp1);
我用过messagebox.show(temp1),并且在temp1中有一个值。该错误显示在程序的第一行。
这是我的代码的一部分。c#:未将对象引用设置为对象的实例
List<DateTime>[] newarraydate1 = new List<DateTime>[70];
DateTime temp1 = arraydate1[k][aa];
newarraydate1[k].Add(temp1);
我用过messagebox.show(temp1),并且在temp1中有一个值。该错误显示在程序的第一行。
您正在声明一个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);
当您创建一个数组,你只创建了包含结构。其成员初始化为默认值,在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();
如果是故意的,你创建一个阵列的名单DateTime
s,您必须首先在条目中创建每个列表
newarraydate1[k] = new List<DateTime>();
只有那么你可以Add
到k
列表(如你问题的最后一行代码)。