【发布时间】:2018-05-05 11:25:00
【问题描述】:
我正在上入门级编程课程。我们最近一直在研究对象,并被要求制作一个程序,该程序可以获取一些用户输入,然后创建具有我们赋予它们的属性的动物对象。我们只需要制作 2 个对象,但我想自己分拆并创建一个程序,要求:
对于一些输入,然后它将该信息放入一个未声明的对象数组中,称为 Animal 类的 animal。然后它会询问您是否要制作另一种动物,如果是,它会重复输入并将其放入数组中的下一个元素中。
我无法让它运行,我很确定我没有正确初始化数组,我查看了整个堆栈溢出但我找不到任何可以让我创建对象数组的东西未指定的大小。我想创建一个新对象,并将其构造函数值放入未指定大小的数组的元素中。
这是我目前遇到的 2 个错误:
错误 CS0650 错误的数组声明器:要声明托管数组的秩 说明符在变量的标识符之前。声明固定大小 缓冲区字段,在字段类型前使用固定关键字
错误 CS0270 无法在变量声明中指定数组大小 (尝试使用“新”表达式进行初始化)
这是我的主要代码:
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++;
}
}
}
}
这是我的动物课:
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.");
}
}
}
我期待学习如何创建大小未定的对象数组。
【问题讨论】:
-
这有点超出你现在的位置。然而,作为即将发生的事情的一个小预览:当您处理未知大小时,数组不是您想要使用的类型。解决方案是实现一个集合,然后在每次您想添加另一个动物时添加到该集合中。
-
您可以使用
List<Animal>而不是Animal[]。然后你可以拨打thatList.Add(new Animal( .. )); -
使用
List<Animal>而不是Animal[]。 -
您还想在循环上方声明/创建该列表,而不是在循环内部。