I have a simple class, Employee, and another class, Company, which contains an array of employees. The company class has 2 nested classes with iterators. One orders the items from first to last, and the second one reverses the order. The NormalEnumeration is the default. When I attempt to use ReverseOrder" in a foreach loop, I get this error:
foreach statement cannot operate on variables of type 'Zadanie_1.Company.ReverseEnumeration' because 'Zadanie_1.Company.ReverseEnumeration' does not contain a public definition for 'GetEnumerator'
My questions is: How can I implement the custom iterators?
public class Employee
{
private string surname, position;
public string Stanowisko { get { return position; } }
public Employee (string nazwisko, string stanowisko)
{
this.surname = nazwisko;
this.position = stanowisko;
}
public override string ToString()
{
return string.Format("nazwisko: {0}, stanowisko: {1}", surname, position);
}
}
public class Company:IEnumerable
{
string name;
private Employee[] employeeArray;
public Company(string nazwa, Employee[] pracownicy)
{
this.name = nazwa;
this.employeeArray = pracownicy;
}
public IEnumerator GetEnumerator()
{
//foreach (Pracownik item in pracownicy)
//{
// yield return item;
//}
return new NormalEnumeration(this);
}
public IEnumerator Ordered()
{
return new NormalEnumeration(this);
}
public override string ToString()
{
return string.Format("Nazwa firmy: {0}, liczba pracowników: {1}", name, employeeArray.Length);
}
public class ReverseEnumeration : IEnumerator
{
Company f;
int counter;
public ReverseEnumeration(Company f)
{
this.f = f;
counter = f.employeeArray.Length;
}
public object Current
{
get
{
Console.WriteLine("Current");
return f.employeeArray[counter];
}
}
public bool MoveNext()
{
if (counter > 0)
{
Console.WriteLine("Move next:");
counter--;
return true;
}
else
return false;
}
public void Reset()
{
counter = f.employeeArray.Length;
}
}
public class NormalEnumeration : IEnumerator
{
Company f;
int counter = -1;
public NormalEnumeration(Company f)
{
this.f = f;
}
public object Current
{
get
{
Console.WriteLine("Current");
return f.employeeArray[counter];
}
}
public bool MoveNext()
{
if (counter >= f.employeeArray.Length-1)
return false;
else
{
counter++;
return true;
}
}
public void Reset()
{
counter = -1;
}
}
}