2016-12-10 93 views
-1

我正在做我的學校作業。我有一個名爲「Person」的類,使用這個類時,用戶必須爲Person類的對象,他的姓氏等添加一個名稱。我在想,是否有可能在循環中自動定義變量?我有一個用戶輸入個人數據的循環。循環看起來是這樣的:是否可以在循環中自動聲明變量? c#

for (int n = 0; n < 20; n++) 
    { 
    Console.WriteLine("Input name of person no. {0}: ", n); 
    name = Console.ReadLine(); 
    Console.WriteLine("Input surname of person no. {0}", n); 
    surname = Console.ReadLine(); 

    Person pers+n = new Person(name, surname); 
    arr[n] = pers+n; 
    } 

所以聲明一個變量就像pers + n。我不知道如何在這個循環中反過來定義Person對象。謝謝!

+0

當然,乾脆去:'字符串名稱=' – Gustav

+1

你在想:「我創造的第n個人「 - 但你不是。你只是創建一個人,然後把它放在你陣列的第n個地方。或者,也許我沒有得到你 – SimpleVar

回答

2

可以使用

for (int n = 0; n < 20; n++) 
    { 
    Console.WriteLine("Input name of person no. {0}: ", n); 
    name = Console.ReadLine(); 
    Console.WriteLine("Input surname of person no. {0}", n); 
    surname = Console.ReadLine(); 

    Person pers = new Person(name, surname); 
    arr[n] = pers; 
    } 
0

添加類持有人的集合。

public class Persons: List<Person> {} 

和創建這個集合的Persons外循環的一個實例,然後在循環中添加的每個新Person到此集合。

Persons = new Persons(); 
for (int n = 0; n < 20; n++) 
{ 
    Console.WriteLine("Input name of person no. {0}: ", n); 
    name = Console.ReadLine(); 
    Console.WriteLine("Input surname of person no. {0}", n); 
    surname = Console.ReadLine(); 
    persons.Add(new Person(name, surname)); 
} 

集合中的各個Person對象可以像數組persons[index]

0

SimpleVar回答我的問題來訪問。謝謝! 解決方案:

for (int n = 0; n < 20; n++) 
{ 
Console.WriteLine("Input name of person no. {0}: ", n); 
name = Console.ReadLine(); 
Console.WriteLine("Input surname of person no. {0}", n); 
surname = Console.ReadLine(); 

Person pers = new Person(name, surname); 
arr[n] = pers; 
} 

+0

這是我的回答 – Eldeniz

+0

@Eldeniz不要小氣,我們幫助他。 – SimpleVar

+0

@SimpleVar我同意你的意見,但我希望他接受我的回答 – Eldeniz

1

嘗試列表對象

  List<Person> people = new List<Person>(); 
     for (int n = 0; n < 20; n++) 
     { 
      Console.WriteLine("Input name of person no. {0}: ", n); 
      name = Console.ReadLine(); 
      Console.WriteLine("Input surname of person no. {0}", n); 
      surname = Console.ReadLine(); 

      Person newPerson = new Person(name, surname); 
      people.Add(newPerson); 
     } 
相關問題