2015-08-28 37 views
3

這裏是我的階級結構:如何在列表類型的類上使用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()'

任何人都可以幫我嗎?

+9

刪除':IEnumerable' - 你沒有實現它。 –

+1

您還需要確保'lstEmployee'在您使用它之前被初始化。您可能希望將一個構造函數添加到'Emp_Details'並在那裏執行。即使將其設置爲空列表也比沒有好。 –

回答

4

問題是你在你的語法,你Emp_Details類實現IEnumerable聲明瞭,但你實際上並沒有實現它。你可以簡單地刪除該聲明,並直接枚舉基礎列表正如其他人的建議,或者如果你真的想Emp_Details自己是枚舉的,你必須實現IEnumerableGetEnumerator方法(簡單地返回內部列表的枚舉):

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_Details類似乎是一個集合,它是有道理的實現集合接口也和暴露AddRemove等方法,而不是暴露直接在底層lstEmployee

5

只需從Emp_Details的聲明卸下底座接口:

public class Emp_Details 
{ 
    public List<Employee> lstEmployee{ get; set; } 
} 
+0

第一次只使用它。但它給了我例外,它沒有包含'GetEnumerator'的公共定義 –

+0

什麼是確切的異常文本(或錯誤消息)? – Dmitry

0

您必須實現Ienumerable的GetEnumerator方法!

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


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