是msdn中的一个经典例子。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 使用泛型类实现Node链 { class Program { static void Main(string[] args) { GenericList<int> G = new GenericList<int>(); for (int i = 1; i <= 5; i++) { G.AddHead(5); } //不实现GenericList中的IEnumrator<>,则foreach不可用 foreach (int i in G) { System.Console.Write(i + " "); } System.Console.WriteLine("/nDone"); System.Console.ReadLine(); } } //Node链类 class GenericList<T> { //私有类Node private class Node { public Node(T t) { this.tvalue = t; this.next = null; } private T tvalue; //下一个节点定义在Node类的内部就可以形成链 private Node next; public Node nextNode { get { return this.next; } set { this.next = value; } } public T Tvalue { get { return this.tvalue; } set { this.tvalue = value; } } } //泛型类的构造函数不含<> public GenericList() { this.head = null; } //链的头节点 private Node head; public void AddHead(T tt) { //GenericList<T>.可省略 Node n = new GenericList<T>.Node(tt); //将新加入的节点n设置为头节点,原来的头节点成为next n.nextNode = this.head; this.head = n; } public IEnumerator<T> GetEnumerator() { Node current = this.head; while (current != null) { //yield,在迭代器块中用于向枚举数对象提供值或发出迭代结束信号,返回值必须为T类型 yield return current.Tvalue; current = current.nextNode; } } } }
不实现IEnumerable<>接口,则foreach不可用。foreach每次yield的类型是<>内的类型。
也可以通过IEnumerator<>枚举,如下:
private void Form1_Load(object sender, EventArgs e) { GenericList<string> list = new GenericList<string>(); list.AddHead("zhangsan"); list.AddHead("lisi"); list.AddHead("wanger"); list.AddHead("chensan"); list.AddHead("zhaoliu"); IEnumerator<string> enu = list.GetEnumerator(); bool bln = enu.MoveNext(); while (bln) { Console.WriteLine(enu.Current); bln = enu.MoveNext(); } }