[英]Index was out of range. Must be non-negative and less than the size of the collection. 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();
}
}
由于您没有将任何项目添加到列表newAnimals
,因此它为空,因此索引0上没有项目。
创建Animal
的实例,然后Add
其Add
(我将其重命名为类名,因为它是单数形式):
Animal animal = new Animal();
// do you magic
newAnimals.Add(animal);
此后 ,您可以检索索引为0的项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.