我遇到這個錯誤有更復雜的模型,但它的List
對象的行爲:通過索引設置對象列表時,索引是否超出範圍?
List<int> numbers= new List<int>();
numbers[0] = 12; //The error occurs here
Console.WriteLine(numbers[0]);
的錯誤是:
指數超出範圍。必須是非負的並且小於 的大小。
編輯
我知道Add()
和Insert()
,但我不知道爲什麼這個奇怪的錯誤發生。
我遇到這個錯誤有更復雜的模型,但它的List
對象的行爲:通過索引設置對象列表時,索引是否超出範圍?
List<int> numbers= new List<int>();
numbers[0] = 12; //The error occurs here
Console.WriteLine(numbers[0]);
的錯誤是:
指數超出範圍。必須是非負的並且小於 的大小。
編輯
我知道Add()
和Insert()
,但我不知道爲什麼這個奇怪的錯誤發生。
你需要調用Add
方法上List
這樣的:
numbers.Add(12)
如果需要使用索引來訪問,你需要填充列表,那麼你可以使用numbers[0]
檢索第一要素。
要初始化列表:
List<int> numbers = new List<int>
{
12,
15,
18
};
現在,numbers[1]
將返回15
您試圖訪問一個索引(0)不存在的,因爲你是初始化一個空的List
。您應該撥打Add()
方法。
List<int> numbers= new List<int>();
numbers.Add(12);
Console.WriteLine(numbers[0]);
當您創建新列表<>對象時,它沒有任何值,因此沒有索引。
這就是爲什麼當您嘗試訪問列表中的第0項時出現錯誤(如果您知道Java的話,就像是IndexOutOfBoundsException)。
使用列表中的Add方法將一個新項目放入它中,而不是嘗試通過索引設置它。
numbers.Add(12)
此方法將給定值附加到列表的末尾,併爲其創建適當的索引。
(在Sahuagin鏈接的問題中,查找'list [0] = 42; // exception'。) – greybeard