如何在List类的类上使用foreach循环?

时间:2015-08-28 09:35:14

标签: c# foreach

这是我的班级结构:

public class Emp_Details : IEnumerable
{
    public List<Employee> lstEmployee{ get; set; }
}
public class Employee
{        public string Name{ get; set; }
    public int Age{ get; set; }
    public string Address{ get; set; }
}

以下是我要做的事情:

Emp_Details obj = new Emp_Details();
obj.lstEmployee = new List<Employee>();
Employee objEmp= new Employee();
objEmp.Name="ABC";
objEmp.Age=21;
objEmp.Address="XYZ";
obj.lstEmployee.Add(objEmp);
foreach(var emp in obj)
{
              //some code
}

我想在List<Employee> lstEmployee上使用foreach 但我得到了

  

Emp_Details没有实现接口成员'System.Collections.IEnumerable.GetEnumerator()'

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:5)

只需从Emp_Details

的声明中删除基接口即可
public class Emp_Details
{
    public List<Employee> lstEmployee{ get; set; }
}

答案 1 :(得分:4)

问题是你在语法中声明你的Emp_Details类实现了IEnumerable,但你实际上并没有实现它。您可以直接删除声明并直接枚举其他人建议的基础列表,或者如果您确实希望Emp_Details本身可以枚举,则必须实现IEnumerable&#39; s {{1方法(只需返回内部列表&#39;枚举器):

GetEnumerator

最好隐式实现Generic public class Emp_Details : IEnumerable<Employee> { public List<Employee> lstEmployee { get; set; } public Emp_Details() { this.lstEmployee = new List<Employee>(); } public IEnumerator<Employee> GetEnumerator() { return lstEmployee.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class Employee { public string Name { get; set; } public int Age { get; set; } public string Address { get; set; } } 接口,明确实现非通用IEnumerable<T>版本以增加类型安全性。现在,您可以迭代IEnumerable的实例:

Emp_Details

此外,由于您的Emp_Details empDetails = new Emp_Details(); // add employees to the inner list empDetails.lstEmployee.Add(new Employee(...)); empDetails.lstEmployee.Add(new Employee(...)); empDetails.lstEmployee.Add(new Employee(...)); // iterate over empDetails using foreach foreach(Employee emp in empDetails) { // } 类似乎是一个集合,因此实现集合接口并公开Emp_DetailsAdd等方法而不是公开底层是有意义的。直接Remove

答案 2 :(得分:0)

您必须实现Ienumerable的GetEnumerator方法!

public class Emp_Details : IEnumerable
    {
        public List<Employee> lstEmployee { get; set; }


        public IEnumerator GetEnumerator()
        {
            throw new NotImplementedException("You must implement this");
        }
    }