c# - 对于抛出的每个错误,不包含“getenumerator”的公共实例定义
问题描述
我正在尝试使用foreach
方法遍历包含学生数据的列表,但是出现错误QA does not contain a public instance definition for 'getenumerator' for each
。
我的 QA 课程如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Test
{
class QA
{
private List<Student> students;
public QA()
{
students = new List<Student>();
string line;
using (StreamReader reader = new StreamReader("/Users/jvb/Desktop/Students.txt"))
{
line = reader.ReadLine();
var s = line.Split(',');
int id = int.Parse(s[0]);
int houseNo = int.Parse(s[3]);
var status = int.Parse(s[7]);
Student sData = new Student(id, s[1], s[2], houseNo, s[4], s[5], s[6], (StudentStatus)status);
AddStudent(sData);
}
}
public List<Student> GetStudents()
{
return students;
}
public void AddStudent(Student student)
{
students.Add(student);
}
}
}
这只是循环遍历具有各种数据位的文本文件并将每个学生添加到students
列表中。在我的program.cs
文件中,我创建了一个 QA 类的实例,并尝试像这样循环遍历它:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
QA students = new QA();
foreach (var s in students)
{
Console.WriteLine(s.GetStudents());
}
}
}
}
我对 c# 很陌生,有人愿意解释我误解/做错了什么吗?
解决方案
您是不可枚举的直接使用对象,您必须访问它的成员,该成员已实现 IList 并且是可枚举的。
你做错了。
您正在迭代不可迭代的类对象。你不需要foreach。
static void Main(string[] args)
{
QA students = new QA();
var studentList= s.GetStudents(); //you get all the students not you can iterate on this lidt
foreach(var student in studentList)
{
//here you can access student property like
Console.WriteLine(student.Name); //I assume Name is a property of Student class
}
}