对于抛出的每个错误,均不包含“ getenumerator”的公共实例定义

时间:2018-10-14 11:12:39

标签: c#

我正在尝试使用foreach方法遍历包含学生数据的列表,但是出现错误QA does not contain a public instance definition for 'getenumerator' for each

我的质量检查课程如下:

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#还是很陌生,有人可以介意解释我的误解/做错了吗?

1 个答案:

答案 0 :(得分:1)

您是不可枚举的直接使用对象,您必须访问实现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
     }
    }