我一直在寻找一个循环内创建一个新的对象,发现一些答案和主题,但它的方式太难理解。使它与列表和数组等。在循环中创建对象
我想要做的是,从用户(让说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();
}
}
我知道我必须创建对象与数组或列表。但我并不真正了解如何在他们按人创建后访问它们。
其他两个'}'在哪里? – 2014-12-06 19:44:29
请使用[Upper Camel Case](http://c2.com/cgi/wiki?UpperCamelCase)作为课程名称,例如'类人'。 – 2014-12-06 19:52:31
另外,您需要一个数组或列表。这不是“太难”,它是如何使用同类对象集合进行编程,而不是通过赋予它们不同的名称。 – 2014-12-06 19:54:02