2012-02-19 62 views
0
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]在那裏,我不得不添加空對象來避免超出範圍的錯誤。

請幫忙嗎?

+0

添加已經給出的良好答案,您可以將int傳遞給列表的構造函數以用作列表的容量。 – 2012-02-19 17:20:39

回答

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

謝謝,知道這很容易。 – saturn 2012-02-19 16:37:00

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

你做

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循環正在執行)纔會有節點。在一個數組中,引用所有元素的空間是先分配的,這樣您可以立即訪問它們,但不能動態修改數組的大小。