2014-12-06 100 views
2

我一直在寻找一个循环内创建一个新的对象,发现一些答案和主题,但它的方式太难理解。使它与列表和数组等。在循环中创建对象

我想要做的是,从用户(让说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(); 
    } 
} 

我知道我必须创建对象与数组或列表。但我并不真正了解如何在他们按人创建后访问它们。

+0

其他两个'}'在哪里? – 2014-12-06 19:44:29

+0

请使用[Upper Camel Case](http://c2.com/cgi/wiki?UpperCamelCase)作为课程名称,例如'类人'。 – 2014-12-06 19:52:31

+0

另外,您需要一个数组或列表。这不是“太难”,它是如何使用同类对象集合进行编程,而不是通过赋予它们不同的名称。 – 2014-12-06 19:54:02

回答

1

这是相当先进的,以创建动态类(对象的实际名称不同)。换句话说,做你所要求的比创建一个List或一个数组更难。如果你花一两个小时学习收藏品,它将长期得到回报。

另外,您可能会考虑将Name属性添加到您的Person类中,然后您可以为每个创建的人设置不同的设置。

正如其他人所说,你需要将它们存储在一个数组或列表:

public class Person 
{ 
    public string Name { get; set; } 
} 

static void Main(string[] args) 
{ 
    Console.Write("How many persons you want to add?: "); 
    int p = int.Parse(Console.ReadLine()); 

    var people = new List<Person>(); 

    for (int i = 0; i < p; i++) 
    { 
     // Here you can give each person a custom name based on a number 
     people.Add(new Person { Name = "Person #" + (i + 1) }); 
    } 
} 

下面是访问从列表中Person并让用户更新的信息的一种方式的例子。请注意,我已经添加了几个属性的Person类:

public class Person 
{ 
    public string Name { get; set; } 
    public DateTime DateOfBirth { get; set; } 
    public string Address { get; set; } 
    public int Age 
    { 
     // Calculate the person's age based on the current date and their birthday 
     get 
     { 
      int years = DateTime.Today.Year - DateOfBirth.Year; 

      // If they haven't had the birthday yet, subtract one 
      if (DateTime.Today.Month < DateOfBirth.Month || 
       (DateTime.Today.Month == DateOfBirth.Month && 
       DateTime.Today.Day < DateOfBirth.Day)) 
      { 
       years--; 
      } 

      return years; 
     } 
    } 
} 

private static void GenericTester() 
{ 
    Console.Write("How many persons you want to add?: "); 
    string input = Console.ReadLine(); 
    int numPeople = 0; 

    // Make sure the user enters an integer by using TryParse 
    while (!int.TryParse(input, out numPeople)) 
    { 
     Console.Write("Invalid number. How many people do you want to add: "); 
     input = Console.ReadLine(); 
    } 

    var people = new List<Person>(); 

    for (int i = 0; i < numPeople; i++) 
    { 
     // Here you can give each person a custom name based on a number 
     people.Add(new Person { Name = "Person" + (i + 1) }); 
    } 

    Console.WriteLine("Great! We've created {0} people. Their temporary names are:", 
     numPeople); 

    people.ForEach(person => Console.WriteLine(person.Name)); 

    Console.WriteLine("Enter the name of the person you want to edit: "); 
    input = Console.ReadLine(); 

    // Get the name of a person to edit from the user 
    while (!people.Any(person => person.Name.Equals(input, 
     StringComparison.OrdinalIgnoreCase))) 
    { 
     Console.Write("Sorry, that person doesn't exist. Please try again: "); 
     input = Console.ReadLine(); 
    } 

    // Grab a reference to the person the user asked for 
    Person selectedPerson = people.First(person => person.Name.Equals(input, 
     StringComparison.OrdinalIgnoreCase)); 

    // Ask for updated information: 
    Console.Write("Enter a new name (or press enter to keep the default): "); 
    input = Console.ReadLine(); 
    if (!string.IsNullOrWhiteSpace(input)) 
    { 
     selectedPerson.Name = input; 
    } 

    Console.Write("Enter {0}'s birthday (or press enter to keep the default) " + 
     "(mm//dd//yy): ", selectedPerson.Name); 
    input = Console.ReadLine(); 
    DateTime newBirthday = selectedPerson.DateOfBirth; 

    if (!string.IsNullOrWhiteSpace(input)) 
    { 
     // Make sure they enter a valid date 
     while (!DateTime.TryParse(input, out newBirthday) && 
      DateTime.Today.Subtract(newBirthday).TotalDays >= 0) 
     { 
      Console.Write("You must enter a valid, non-future date. Try again: "); 
      input = Console.ReadLine(); 
     } 
    } 
    selectedPerson.DateOfBirth = newBirthday; 


    Console.Write("Enter {0}'s address (or press enter to keep the default): ", 
     selectedPerson.Name); 

    input = Console.ReadLine(); 
    if (!string.IsNullOrWhiteSpace(input)) 
    { 
     selectedPerson.Address = input; 
    } 

    Console.WriteLine("Thank you! Here is the updated information:"); 
    Console.WriteLine(" - Name ............ {0}", selectedPerson.Name); 
    Console.WriteLine(" - Address ......... {0}", selectedPerson.Address); 
    Console.WriteLine(" - Date of Birth ... {0}", selectedPerson.DateOfBirth); 
    Console.WriteLine(" - Age ............. {0}", selectedPerson.Age); 
} 
0

您可以在C#中创建动态命名的变量。

你需要的是persons集合:

var persons = new List<person>(); 

for (int i = 0; i < p; i++) 
{ 
    persons.Add(new person()); 
} 
+1

嗨Selman22。 OP要求是不可能的?正确? – Christos 2014-12-06 19:47:08

+2

@Christos从技术上讲,您可以在C#中创建动态程序集,类,方法。但在这种情况下,这是不值得一提的。这只会造成混淆 – 2014-12-06 19:49:23

+0

好。非常感谢你! – Christos 2014-12-06 19:50:36

1

最接近的事在做你所要求的是创建一个字典:

using System; 
using System.Collections.Generic; 

public class Program 
{ 
    public static void Main() 
    { 
     var dictionary = new Dictionary<string, Person>(); 

     Console.Write("How many persons you want to add?: "); 
     int p = int.Parse(Console.ReadLine()); 

     for (int i = 0; i < p; i++) 
     { 
      dictionary.Add("NewPerson" + i, new Person()); 
     } 

     // You can access them like this: 
     dictionary["NewPerson1"].Name = "Tim Jones"; 
     dictionary["NewPerson2"].Name = "Joe Smith"; 
    } 

    public class Person 
    { 
     public string Name { 
      get; 
      set; 
     } 
    } 
} 
+0

请记住,OP指出数组“太难了”。我不认为引入字典会帮助任何人。 – 2014-12-06 19:54:49

+0

@JonathonReinhart - 是的,但正如你在上面的评论中指出的那样,没有“太难”的方式。它们是根本性的。 – Icemanind 2014-12-06 19:56:13

0

数组和列表是基本的构建模块。他们不应该很难。但如果你不想与他们打交道,请尝试创建一个方法,其职责是给你新的对象给予计数。

static void Main(string[] args) 
    { 
     Console.Write("How many persons you want to add?: "); 
     int p = int.Parse(Console.ReadLine()); 

     var newPersons = CreatePersons(p); 

     foreach (var person in newPersons) 
     { 
      Console.WriteLine("Eneter age for Person :" person.Name); 
      person.Age = Console.ReadLine(); 
     } 

    } 

    static IEnumerable<Person> CreatePersons(int count) 
    { 
     for (int i = 0; i < count; i++) 
     { 
      yield return new Person{ Name="newPerson" +1 }; 
     } 
    } 
0

试试这个。

我建立的人(对象)的阵列的第一(如创建对象阵列)

然后我将其赋值给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); 
     Persons[] newPersons = new Persons[count]; 

     for (int i = 0; i < count; i++) 
     { 
      newPersons[i] = new Persons(); 
      newPersons[i].id = i+1; 
      Console.Write("Write name for person " + (i+1) + "\t"); 
      newPersons[i].name = Console.ReadLine(); 
      Console.Write("Write age for person " + (i + 1) + "\t"); 
      newPersons[i].age = int.Parse(Console.ReadLine()); 
      Console.Write("Write adress for person " + (i + 1) + "\t"); 
      newPersons[i].adress = Console.ReadLine(); 
     } 

     Console.WriteLine("\nPersons Name \tAge \tAdresss \n"); 
     for (int i = 0; i < count; i++) 
     { 
      Console.WriteLine(newPersons[i].name + "\t\t" + newPersons[i].age + "\t" + newPersons[i].adress); 
     } 

     Console.ReadKey(); 
    } 
}