簡體   English   中英

錯誤C#:索引超出范圍。 必須為非負數且小於集合的大小

[英]Error C#: Index was out of range. Must be non-negative and less than the size of the collection

我在for循環中創建對象並將它們添加到列表中時遇到了問題。 該程序以“您要添加多少?”開頭。 無論我寫什么,它都會向我顯示一條消息:索引超出范圍。 必須為非負數並且小於集合的大小。 怎么了? 抱歉,還有另一個類似的問題,但我找不到答案。 謝謝!

  using System;
using System.Collections.Generic;


class Animals
{

    public int id { get; set; }


    public string name { get; set; }


    public string color { get; set; }     


    public int age { get; set; }

    }

class Program
{
    static void Main(string[] args)
    {
        Console.Write("How much animals you want to add?: ");
        int count = int.Parse(Console.ReadLine());

        var newAnimals = new List<Animals>(count);

        for (int i = 0; i < count; i++)
        {
            newAnimals[i].id = i;

            Console.Write("Write name for animal " + i);
            newAnimals[i].name = Console.ReadLine();

            Console.Write("Write age for animal " + i);
            newAnimals[i].age = int.Parse(Console.ReadLine());

            Console.Write("Write color for animal " + i );
            newAnimals[i].color = Console.ReadLine();

        }

        Console.WriteLine("\nAnimals \tName \tAge \tColor");
        for (int i = 0; i < count; i++)
        {
            Console.WriteLine("\t" + newAnimals[i].name + "\t" + newAnimals[i].age + "\t" + newAnimals[i].color);
        }

        Console.ReadLine();
    }
}

var newAnimals = new List<Animals>(count); 創建一個具有特定容量的空列表(內部數據結構無需調整大小即可容納的元素總數)

正如在MSDN中關於此構造函數的說法:

初始化List類的新實例,該實例為空並具有指定的初始容量。

您需要使用Add方法將元素添加到列表中。

newAnimals.Add (new Animal() {id = 1, name = "name"});

由於您沒有將任何項目添加到列表newAnimals ,因此它為空,因此索引0上沒有項目。

創建Animal的實例,然后AddAdd (我將其重命名為類名,因為它是單數形式):

Animal animal = new Animal();

// do you magic

newAnimals.Add(animal);

此后 ,您可以檢索索引為0的項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM