IEnumerable与IEnumerator
static void Main(string[] args) { MyClass cl=new MyClass(); foreach (Notm notm in cl) { Console.WriteLine("{0}+l,{1}+h",notm.l,notm.h); } Console.ReadLine(); //要反转的值序列 foreach (Notm notm in cl.GetEnumerableReverse()) { Console.WriteLine("{0}+l,{1}+h", notm.l, notm.h); } Console.ReadLine(); foreach (Notm notm in cl.GetMaxEnumerable(200)) { Console.WriteLine("{0}+l,{1}+h", notm.l, notm.h); } Console.ReadLine(); }
枚集器实现迭代器
为了实现迭代器接口 MyClass先要实现枚集器接口 因此myclass要继承IEnumerable 枚集接口
public class MyClass : IEnumerable { private Notm[] notms=new Notm[5]; public MyClass() { for (int i = 0; i < 5; i++) { notms[i]=new Notm(i+10,i+200); } } //实现迭代 public IEnumerator GetEnumerator() { return notms.GetEnumerator(); //yield return notms[1]; //yield return notms[4]; } public IEnumerable GetMaxEnumerable(int h) { foreach (Notm notm in notms) { if (notm.h>h) { yield return notm; } } } public IEnumerable GetEnumerableReverse() {//要反转的值序列 return notms.Reverse(); } }
publicclass Notm
{ public int l { get; set; } public int h { get; set; } public Notm(int l, int h) { this.l = l; this.h = h; } }
知识来源 http://v.youku.com/v_show/id_XMTUyODk3NzU5Ng==.html#paction
浙公网安备 33010602011771号