【问题标题】:Creating Objects in loop循环创建对象
【发布时间】:2015-10-19 18:04:14
【问题描述】:

只是寻找一种在循环中从同一类创建一些(20)个对象的方法 有什么办法吗?

我尝试使用 Loopcount Int 作为 num,但没有运气。有什么想法吗?

 static void Main(string[] args)
 {
     Student[] aStudent = new Student[20];

     for (int i = 0; i < 20; i++)
     {
         Console.WriteLine("Please enter the 2 grades for student num " + i+ " \nif there is no grade , enter -1");
         aStudent[i].FirstGrade = int.Parse(Console.ReadLine());
         aStudent[i].SecondGrade = int.Parse(Console.ReadLine());
     }
}

【问题讨论】:

  • 你当然可以。首先,您需要一种编程语言。然后你需要一堂课。然后你需要一个你尝试的例子。然后我们会有想法。
  • 对不起 :) 我是菜鸟,我会编辑帖子
  • 我能提出宝贵的建议吗?不要使用原始数组,除非你有很好的理由这样做;你应该使用 List students = new List();

标签: c# object for-loop


【解决方案1】:

您已经创建了一个数组,但尚未初始化数组中的项目。最简单的更改是在循环内创建一个新实例:

for (int i = 0; i < 20; i++)
{
    aStudent[i] = new Student();
    Console.WriteLine("Please enter the 2 grades for student num " + i+ " \nif there is no grade , enter -1");
    aStudent[i].FirstGrade = int.Parse(Console.ReadLine());
    aStudent[i].SecondGrade = int.Parse(Console.ReadLine());
}

【讨论】:

  • 我会将 aStudent 添加到对象列表中,以便您可以在 for 循环之外使用
猜你喜欢
  • 1970-01-01
  • 2012-11-29
  • 2015-02-23
  • 2016-11-11
  • 1970-01-01
  • 2020-08-08
  • 2015-02-04
  • 1970-01-01
相关资源
最近更新 更多