循环中创建对象
本文关键字:创建对象 循环 | 更新日期: 2023-09-27 18:18:27
只是寻找一种在循环中从同一个类创建一些(20)个对象的方法有办法吗?
我尝试在for查找中使用循环计数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());
}
}
您已经创建了一个数组,但尚未初始化数组中的项。最简单的改变就是在循环中创建一个新实例:
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());
}