循环创建对象

时间:2015-10-19 18:04:14

标签: c# object for-loop

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

我尝试使用Loopcount Int作为数字而没有运气..任何想法?

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

1 个答案:

答案 0 :(得分:0)

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

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());
}
相关问题