列表数组初始化c#

时间:2012-02-19 16:30:49

标签: c# arrays list object

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]在那里,我必须添加空对象以获得outofrange错误是没有意义的。

请帮忙吗?

3 个答案:

答案 0 :(得分: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)
  };

答案 1 :(得分: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)
};

你完成了

答案 2 :(得分: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循环正在进行。在数组中,前面分配了所有元素引用的空间,因此您可以立即访问它们,但不能动态修改数组的大小。

相关问题