【发布时间】:2012-02-19 16:30:49
【问题描述】:
List<authorinfo> aif = new List<authorinfo>();
for (int i = 0; i < 5; i++)
{
aif.Add(null);
}
aif[0] = new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844);
aif[1] = new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972);
aif[2] = new authorinfo("The Three Musketeers", "Alexandre", "Dumas", 1844);
aif[3] = new authorinfo("Robinson Crusoe", "Daniel", "Defoe", 1719);
aif[4] = new authorinfo("2001: A Space Odyssey", "Arthur", "Clark", 1968);
//authorinfo ai = new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844);
foreach (authorinfo i in aif)
{
Console.WriteLine(i);
}
好吧,当我删除顶部的 for 循环时,程序不会启动,为什么?因为我需要将 null 添加到列表中。
我知道我做错了。我只希望 aif[0-4] 在那里,我必须添加空对象才能避免出现超出范围的错误是没有意义的。
请帮忙?
【问题讨论】:
-
除了已经给出的好答案之外,您还可以将一个 int 传递给列表的构造函数以用作列表的容量。