【问题标题】:Error C#: Index was out of range. Must be non-negative and less than the size of the collection错误 C#:索引超出范围。必须是非负数且小于集合的大小
【发布时间】:2016-06-14 12:56:24
【问题描述】:

我在 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();
    }
}

【问题讨论】:

  • 如果您知道初始(和最终)大小,您也可以使用Animals[]。然后你可以用你的方式初始化数组(通过索引)。如果以后大小可能会改变,您应该使用List&lt;Animals&gt;List&lt;&gt;.Add 添加元素。

标签: c# outofrangeexception


【解决方案1】:

由于您没有将任何项目添加到列表 newAnimals,因此它是空的,因此它在索引 0 上没有项目。

创建Animal 的实例,然后创建Add 它(我重命名了类名,因为它是单数):

Animal animal = new Animal();

// do you magic

newAnimals.Add(animal);

之后,您可以检索索引 0 处的项目。

【讨论】:

    【解决方案2】:

    var newAnimals = new List&lt;Animals&gt;(count); 使用特定的Capacity 创建一个空列表(内部数据结构可以容纳的元素总数,无需调整大小)

    正如 MSDN 关于这个构造函数所说的:

    初始化 List 类的新实例,该实例为空且具有 指定的初始容量。

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

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

    【讨论】:

      猜你喜欢
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多