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]在那裏,我不得不添加空對象來避免超出範圍的錯誤。
請幫忙嗎?
添加已經給出的良好答案,您可以將int傳遞給列表的構造函數以用作列表的容量。 – 2012-02-19 17:20:39