C# IEnumerable

 

Для того аби пройтися по об'єктах колекції в циклі foreach вони мають підтримувати інтерфейси IEnumerable та IEnumerator

foreach (var item in kolektsiya)
{

}

 



public interface IEnumerable
{
  IEnumerator GetEnumerator(); // повертає посилання на інший інтерфейс
}

public interface IEnumerator
{
  bool MoveNext(); // вперед на один елемент
  object Current { get; } // поточний елемент
  void Reset(); // на початок
}

 


 

class WeekEnumerator : IEnumerator
{
  string[] days;
  int position = -1;
  public WeekEnumerator(string[] days)
  {
    this.days = days;
  }
  public object Current
  {
    get
    {
      if (position == -1 || position >= days.Length)
        throw new InvalidOperationException();
      return days[position];
    }
  }

  public bool MoveNext()
  {
    if (position < days.Length - 1)
    {
      position++;
      return true;
    }
    else
      return false;
  }

  public void Reset()
  {
    position = -1;
  }
}

class Week : IEnumerable
{
  string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };

  public IEnumerator GetEnumerator()
  {
    return new WeekEnumerator(days);
  }

}

 

static void Main(string[] args)
{
  Week week = new Week();

  foreach (var day in week)
  {
    Console.WriteLine(day);
  }

  //IEnumerator vv = week.GetEnumerator();
  //while (vv.MoveNext())
  //{
  // Console.WriteLine(vv.Current);
  //}

  Console.Read();
}

 

Monday
Tuesday
Wednesday
Thursday
Friday