2014-12-06 104 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(); 
    } 
}