Home   Cover Cover Cover Cover
 

IEnumerable

Chap4_Ex1.cs
using System.Collections;

public class CharNode {
  private char c;
  private CharNode next;

  public CharNode(char c) { this.c = c; }

  public CharNode Next {
    get { return next; }
    set { next = value; }
  }

  public char Char {
    get { return c; }
    set { c = value; }
  }
}

public class CharNodeList : IEnumerable {
  private CharNode head;

  // add new node at the begin of the list
  public void Add(char c) {
    CharNode nn = new CharNode(c);
    nn.Next = head;
    head = nn;
  }

  public IEnumerator GetEnumerator() {
    return new CharNodeEnumerator(head);
  }

  public class CharNodeEnumerator : IEnumerator {
    private CharNode cur, head;
    
    public CharNodeEnumerator(CharNode head) {
      this.head = head;
    }

    public object Current {
      get { 
        if(cur == null) return null; 
          else return cur.Char;
      } 
    }

    public bool MoveNext() {
      if(cur == null) cur = head;
      else {
        if(cur.Next == null) return false;
        cur = cur.Next;
      }
      return true;
    }

    public void Reset() {
      cur = null;
    }
  }
}

public class Ch4_Ex1_Test {

  public static void Main(string[] args) {
    CharNodeList list = new CharNodeList();
    list.Add('a');
    list.Add('b');
    list.Add('c');
    list.Add('d');
    foreach(char c in list) 
      System.Console.WriteLine("{0}", c);
  }
}