2012-02-19 56 views
0
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-loop程序不会启动时,为什么?因为我需要将null添加到列表中。list array initialization c#

我知道我这样做是错误的。我只是想让aif [0-4]在那里,我不得不添加空对象来避免超出范围的错误。

请帮忙吗?

+0

添加已经给出的良好答案,您可以将int传递给列表的构造函数以用作列表的容量。 – 2012-02-19 17:20:39

回答

5

只需添加新的对象实例本身:

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) 
    }; 
+0

谢谢,知道这很容易。 – saturn 2012-02-19 16:37:00

1

做这样的:

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) 
}; 

你做

0

当你通过索引访问列表元素像这样,

var myObj = foo[4]; 

您假定集合foo至少有五个(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循环正在执行)才会有节点。在一个数组中,引用所有元素的空间是先分配的,这样您可以立即访问它们,但不能动态修改数组的大小。