我发现了一种类似的解决方案,我试图跟进,但仍未能解决。
我创建了一个公共财产First_Name& amp;姓。 然后使用Arraylist我想得到&打印每个学生的详细信息。但执行代码后,我得到的是空控制台窗口。当我使用断点运行代码时,我看到代码流没有进入foreach循环。请帮助我......
ArrayList studentList = new ArrayList();
public void getStudent()
{
foreach (Student student in studentList)
{
Console.Write("Enter Your First Name: ");
student.First_Name = Console.ReadLine();
Console.Write("Enter Your Last Name: ");
student.Last_Name = Console.ReadLine();
}
}
public void printStudentInformation()
{
foreach (Student student in studentList)
{
Console.WriteLine("-----------------------");
Console.WriteLine("Name Of The Student Is {0} {1}", student.First_Name, student.Last_Name);
Console.WriteLine("-----------------------");
}
}
答案 0 :(得分:2)
首次运行代码时,studentList
中没有学生,foreach
中的getStudent
将不会被执行。创建Student
类的新实例,然后将FirstName
和LastName
存储在student对象中,并将student对象添加到studentList
数组。
public void getStudent()
{
var student = new Student();
Console.Write("Enter Your First Name: ");
student.First_Name = Console.ReadLine();
Console.Write("Enter Your Last Name: ");
student.Last_Name = Console.ReadLine();
studentList.Add(student);
}
答案 1 :(得分:1)
在使用foreach
显示值之前,您必须填充列表。为此,您可以使用以下代码。然后将每个应用于显示内容。因此,方法签名必须改变如下:
public void getStudent()
{
List<Student> StudentList = new List<Student>();
string nextVal = "y";
while (nextVal == "N")
{
var student = new Student();
Console.Write("Enter Your First Name: ");
student.First_Name = Console.ReadLine();
Console.Write("Enter Your Last Name: ");
student.Last_Name = Console.ReadLine();
StudentList.Add(student);
Console.Write("Do you wnat to add more data(Y/N)");
nextVal = Console.ReadKey().ToString();
}
}