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添加到列表中。
我知道我做错了。我只希望aif0-4在那里,我必须添加null对象才不会得到一个outofrange错误,这是没有意义的。
帮帮忙好吗?
发布于 2012-02-20 00:32:28
只需添加新的对象实例本身:
List<authorinfo> aif = new List<authorinfo>();
aif.Add(new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844));
//... and so on现在,您正在使用null作为占位符元素,然后使用索引器覆盖它-您不必这样做(也不应该这样做)。
作为另一种选择,如果您事先知道列表元素,也可以使用collection initializer
List<authorinfo> aif = new List<authorinfo>()
{
new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844),
new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972),
new authorinfo("The Three Musketeers", "Alexandre", "Dumas", 1844)
};发布于 2012-02-20 00:34:11
如下所示:
var aif = new List<authorinfo> {
new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844),
new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972),
new authorinfo("The Three Musketeers", "Alexandre", "Dumas", 1844),
new authorinfo("Robinson Crusoe", "Daniel", "Defoe", 1719),
new authorinfo("2001: A Space Odyssey", "Arthur", "Clark", 1968)
};然后你就完成了
发布于 2012-02-20 00:43:57
当您像这样通过索引访问列表元素时,
var myObj = foo[4];假设集合foo至少有5个(0,1,2,3,4)元素。你会得到一个超出范围的错误,因为在没有for循环的情况下,你试图访问一个没有被分配的元素。
有几种方法可以处理这个问题。最明显的是使用List<>.Add()
List<authorinfo> aif = new List<authorinfo>();
aif.Add(new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844));
aif.Add(new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972);
// ....但是,对于像这样的玩具(家庭作业)问题,您可以在构造时初始化列表:
var authorList = new List<authorinfo>
{
new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844)
,new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972)
, // .....
};关于List<>和其他集合,最有用的事情之一是它们是动态调整大小的,而不是数组。可以将List<>看作是一个链表,它为您处理所有节点连接。和链表一样,List<>只有在添加节点后才会有节点,就像for循环所做的那样。在数组中,所有元素的引用空间都是预先分配的,因此您可以立即访问它们,但不能动态修改数组的大小。
https://stackoverflow.com/questions/9350940
复制相似问题