using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Genericlist<int> mylist = new Genericlist<int>(); for (int x = 0; x < 10; x++) { mylist.addhead(x); } foreach (int i in mylist) { Console.WriteLine(i); } } } public class Genericlist<T> { private class node { public node(T t)//声明的node类的构造函数,带一个T参数 { data = t; next = null; } private node next; public node Next { get { return next; } set { next = value; } } private T data; public T Data { get { return data; } set { data = value; } } } private node head;//创建位于Genericlist类的字段,类型为node的head public Genericlist()//Genericlist类的构造函数 { head = null; } public void addhead(T t)//执行将新node添置于旧head前而形成新head的操作 { node n = new node(t); n.Next = head; head = n; } public IEnumerator<T> GetEnumerator()//这里实现IEnumerator枚举器接口的方法GetEnumerator,所以这个方法名不能改变 { node current = head; while (current != null) { yield return current.Data; current = current.Next; } } } }
由于要实现
foreach (int i in mylist)
这样的迭代,会调用到接口中的GetEnumerator()方法,所以在Genericlist类中只是实现这个方法,因此实现时方法名不可改动~