如何在不知道指定数量的情况下创建对象数组

时间:2017-11-21 20:56:43

标签: c# arrays oop object

我在入门级编程课程中。我们最近一直在讨论对象,并被要求创建一个程序,获取一些用户输入,然后创建具有我们给他们的属性的动物对象。我们只需要制作2个对象,但我想自己创建并创建一个程序,要求:

对于一些输入,然后它将该信息放入一个名为Animal类动物的未声明的对象数组中。然后它询问你是否想制作另一种动物,如果是这样,它会重复输入并将其放入数组中的下一个元素。

我无法让它运行,我很确定我没有正确初始化阵列,我已经查看了堆栈溢出但我无法找到任何内容让我创建一个未指定大小的对象数组。我想创建一个新对象及其构造函数值为一个未指定大小的数组元素。

以下是我目前遇到的2个错误:

  

错误CS0650错误的数组声明符:声明托管数组的等级   说明符在变量的标识符之前。声明固定大小   缓冲区域,在字段类型

之前使用fixed关键字      

错误CS0270无法在变量声明中指定数组大小   (尝试使用' new'表达式初始化)

这是我的主要代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArrayOfObjectsAnimalMaker
{
    class Program
    {
        static void Main(string[] args)
        {
            string another = "y";
            int count = 0;
            string species;
            string age;

            while (another == "y")
            {
                Console.WriteLine("Type in the animal's species: ");
                species = Console.ReadLine();

                Console.WriteLine("Type in the animal's age: ");
                age = Console.ReadLine();

                Animal animal[count] = new Animal(species, age);

                Console.WriteLine("Type y to create another animal or n to end: ");
                another = Console.ReadLine();

                count++;
            }
        }
    }
}

这是我的Animal类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArrayOfObjectsAnimalMaker
{
    class Animal
    {
        private string species;
        private string age;

        public Animal(string s, string a)
        {
            this.species = s;
            this.age = a;
        }

        public void DisplayInfo()
        {
            Console.WriteLine("This is a " + this.species + " that is " + this.age + " years old.");
        }
    }
}

我期待学习如何创建不确定大小的对象数组。

2 个答案:

答案 0 :(得分:4)

您可以使用List<T>

List<T>通过使用大小根据需要动态增加的数组来实现IList<T>

// create a list to hold animals in 
var allAnimals = new List<Animal>();    

while (another == "y")
{
    Console.WriteLine("Type in the animal's species: ");
    species = Console.ReadLine();

    Console.WriteLine("Type in the animal's age: ");
    age = Console.ReadLine();

    // create the animal..
    var newAnimal = new Animal(species, age);
    // ..and add it in the list.
    allAnimals.Add(newAnimal);

    Console.WriteLine("Type y to create another animal or n to end: ");       
    another = Console.ReadLine();
}

答案 1 :(得分:0)

一旦声明,数组的大小是固定的。 拥有动态集合大小的最简单方法是使用List类。 如果您仅限于使用数组,则可以从固定大小的数组开始(例如1)。然后,当您需要更多空间时,您将分配一个比原始数据大两倍的新数组,将原始数组复制到新数组中,然后添加新数据。 您可以根据需要重复此过程。