【问题标题】:Is it possible to do automatic declaration of variabes in loop? c#是否可以在循环中自动声明变量? C#
【发布时间】:2016-12-10 13:17:59
【问题描述】:

我正在做我的学校作业。我有一个名为“Person”的类,使用这个类,用户必须为 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 pers+n = new Person(name, surname);
    arr[n] = pers+n;
   }

所以变量的声明类似于 pers+n。我不知道如何反过来在这个循环中定义 Person 对象。谢谢!

【问题讨论】:

  • 当然,请继续:string name =
  • 你在想“我正在创造第 n 个人”——但你不是。您只是在创建 a 人,然后将其放在数组的第 n 个位置。或者也许我没有让你正确

标签: c# arrays loops variables


【解决方案1】:

你可以使用

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;
   }

【讨论】:

    【解决方案2】:

    尝试一个列表对象

             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);
             }
    

    【讨论】:

      【解决方案3】:

      添加一个类来保存一个人的集合。

      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));
      }
      

      可以像访问数组persons[index] 一样访问集合中的各个Person 对象

      【讨论】:

        【解决方案4】:

        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;
        }
        

        【讨论】:

        • 这是我的答案
        • @Eldeniz 别小气,我们帮了他。
        • @SimpleVar 我同意你的观点,但我希望他接受我的回答
        猜你喜欢
        • 2018-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-19
        • 2022-11-04
        • 1970-01-01
        相关资源
        最近更新 更多