且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

列表数组初始化C#

更新时间:2022-04-13 00:22:01

只需自己添加新的对象实例:

Just add the new object instances themselves:

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

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

Right now you are using null as a placeholder element which you then overwrite using the indexer - you don't have to do this (nor should you).

作为一种替代方法,如果您事先知道列表元素,则也可以使用集合初始化器:

As an alternative and if you know your list elements in advance you could also use the 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)
  };