我想用一个可以在运行时设置的枚举器定义一个集合。
我定义了一个枚举器:
public class JuniorEmployeeEnumerator : IEnumerable<Employee> {
List<Employee> list = new List<Employee>();
public JuniorEmployeeEnumerator(List<Employee> emplist) {
list = emplist;
}
public IEnumerator<Employee> GetEnumerator() {
for (int i = 0; i < list.Count; i++) {
if (list[i].Age < 50) {
yield return list[i];
}
}
}
IEnumerator IEnumerable.GetEnumerator() {
return (GetEnumerator());
}
}
并且集合接受枚举器:
public class EmployeeCollection : IEnumerable<Employee> {
public List<Employee> Employees { get; set; }
public IEnumerable<Employee> EnumeratorType { get; set; }
public EmployeeCollection() {
Employees = new List<Employee>();
}
public IEnumerator<Employee> GetEnumerator() {
return EnumeratorType.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return (GetEnumerator());
}
}
所以,用法应该是:
static void Main(string[] args) {
EmployeeCollection empcoll = new EmployeeCollection();
empcoll.Employees.Add(new Employee("Fatima", 57));
empcoll.Employees.Add(new Employee("Evangeline", 52));
empcoll.Employees.Add(new Employee("Damien", 49));
empcoll.Employees.Add(new Employee("Cameroon", 55));
empcoll.Employees.Add(new Employee("Babu", 24));
Console.Write("Senior Employees \n");
empcoll.EnumeratorType = new JuniorEmployeeEnumerator(empcoll.Employees);
foreach (Employee anEmp in empcoll.GetEnumerator()) {
Console.Write(" " + anEmp.Name + " " + anEmp.Age + "\n");
}
Console.ReadKey();
}
但我得到这个编译错误:
foreach 语句不能对“System.Collections.Generic.IEnumerator”类型的变量进行操作,因为“System.Collections.Generic.IEnumerator”不包含“GetEnumerator”的公共定义
我该如何解决?