列表数组初始化 C#

本文关键字:初始化 数组 列表 | 更新日期: 2023-09-27 18:25:02

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] 在那里,我必须添加空对象才能不出现超出范围的错误是没有意义的。

请帮忙?

列表数组初始化 C#

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

  List<authorinfo> aif = new List<authorinfo>();
  aif.Add(new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844));
  //... and so on

现在,您将null用作占位符元素,然后使用索引器覆盖该元素 - 您不必这样做(也不应该这样做(。

作为替代方案,如果您事先知道列表元素,您还可以使用集合初始值设定项:

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

这样做:

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

你完成了

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

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 循环正在这样做。在数组中,对所有元素的引用空间是预先分配的,因此您可以立即访问它们,但不能动态修改数组的大小。