繁体   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