我一直在搜索如何在循环内创建新对象,找到了一些答案和主题,但是理解起来太难了。需要使用列表和数组等。
我想要做的是,从用户那里获取一个输入(比如3),并创建尽可能多的具有唯一名称的对象。比如newperson1、newperson2、newperson3等。
我的代码看起来像这样:
class person
{
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
for (int i = 0; i < p; i++)
{
person newperson = new person();
}
}
}
有没有办法在对象名称末尾创建以下数字的新对象? 谢谢!
编辑: 我的新代码看起来像这样;我更多地是这样思考的:
class Persons
{
//Person object id
public int id { get; set; }
//Persons name
public string name { get; set; }
//Persons adress
public string adress { get; set; }
//Persons age
public int age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int count = int.Parse(Console.ReadLine());
var newPersons = new List<Persons>(count);
for (int i = 0; i < count; i++)
{
newPersons[i].id = i;
Console.Write("Write name for person " + i);
newPersons[i].name = Console.ReadLine();
Console.Write("Write age for person " + i);
newPersons[i].age = int.Parse(Console.ReadLine());
Console.Write("Write adress for person " + i );
newPersons[i].adress = Console.ReadLine();
}
Console.WriteLine("\nPersons \tName \tAge \tAdress");
for (int i = 0; i < count; i++)
{
Console.WriteLine("\t" + newPersons[i].name + "\t" + newPersons[i].age + "\t" + newPersons[i].adress);
}
Console.ReadKey();
}
}
我知道我必须使用数组或列表来创建对象。但是我并不完全明白在逐个创建后如何访问它们。
class Person
。 - Jonathon Reinhart