sat*_*urn 0 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);
}
Run Code Online (Sandbox Code Playgroud)
好吧,事情是,当我删除顶部的for循环程序不会启动,为什么?因为我需要在列表中添加null.
我知道我这样做的方式不对.我只想要aif [0-4]在那里,我必须添加空对象以获得outofrange错误是没有意义的.
请帮忙?
只需添加新的对象实例:
List<authorinfo> aif = new List<authorinfo>();
aif.Add(new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844));
//... and so on
Run Code Online (Sandbox Code Playgroud)
现在,您正在使用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)
};
Run Code Online (Sandbox Code Playgroud)