.net 可枚举类型的构建方法
数组可以使用foreach遍历数组,其实只要实现GetEnumertor方法的类型都可以使用foreach结构遍历数组。
首先看下代码:
1 //笔类 2 public class Pencil 3 { 4 public string Color { get; set; } 5 6 public int Num { get; set; } 7 } 8 9 //笔盒类 10 public class PencilBox 11 { 12 private Pencil[] pencil = new Pencil[2];//应该使用泛型,这里做演示 13 14 public PencilBox() 15 { 16 pencil[0] = new Pencil() { Color = "Red", Num = 1 }; 17 pencil[0] = new Pencil() { Color = "Black", Num = 2 }; 18 } 19 }
如果想对PencilBox进行遍历呢?可枚举类型构建的两种方式(非泛型):实现IEnumerable接口、yield迭代器方法
实现IEnumerable接口
1 public class PencilBox: IEnumerable//实现IEnumerable接口 2 { 3 private Pencil[] pencil = new Pencil[2]; 4 5 public PencilBox() 6 { 7 pencil[0] = new Pencil() { Color = "Red", Num = 1 }; 8 pencil[1] = new Pencil() { Color = "Black", Num = 2 }; 9 } 10 11 //实现GetEnumerator方法, 12 //这里System.Array已经实现了IEnumerable、IEnumerator接口可以简单委托请求道System.Array 13 public IEnumerator GetEnumerator() 14 { 15 return pencil.GetEnumerator(); 16 } 17 }
yield迭代器方法
1 public class PencilBox//不用实现IEnumerable接口 2 { 3 private Pencil[] pencil = new Pencil[2]; 4 5 public PencilBox() 6 { 7 pencil[0] = new Pencil() { Color = "Red", Num = 1 }; 8 pencil[1] = new Pencil() { Color = "Black", Num = 2 }; 9 } 10 11 //实现GetEnumeratore方法,返回值必须为IEnumerator 12 //使用yield return语法返回对象,yield关键字用来向调用方的foreach返回值 13 //当达到yield return语句后,当前位置存储起来,下次使用迭代器时会从该位置开始执行 14 public IEnumerator GetEnumerator() 15 { 16 foreach (Pencil pencil1 in pencil) 17 { 18 yield return pencil1; 19 } 20 } 21 }
yield 迭代器方法也可以实现可选择迭代,返回局部数据
1 //笔盒类 2 public class PencilBox//不用实现IEnumerable接口 3 { 4 private Pencil[] pencil = new Pencil[3]; 5 6 public PencilBox() 7 { 8 pencil[0] = new Pencil() { Color = "Red", Num = 1 }; 9 pencil[1] = new Pencil() { Color = "Black", Num = 2 }; 10 pencil[2] = new Pencil() { Color = "Blue", Num = 3 }; 11 12 } 13 14 //实现GetEnumeratore方法,返回值必须为IEnumerator 17 public IEnumerator GetEnumerator() 18 { 19 yield return pencil[0]; 20 yield return pencil[2]; 21 } 22 }
yield迭代器也可以带参数,当带参数时返回的是IEnumerable,而不是IEnumerator类型
1 //笔盒类 2 public class PencilBox//不用实现IEnumerable接口 3 { 4 private Pencil[] pencil = new Pencil[3]; 5 6 public PencilBox() 7 { 8 pencil[0] = new Pencil() { Color = "Red", Num = 1 }; 9 pencil[1] = new Pencil() { Color = "Black", Num = 2 }; 10 pencil[2] = new Pencil() { Color = "Blue", Num = 2 }; 11 12 } 13 14 //可随意命方法名 15 //返回IEnumerable类型,而不是IEnumerator 类型 16 public IEnumerable GetEnumerator(int num) 17 { 18 foreach (Pencil pencil1 in pencil) 19 { 20 if (pencil1.Num > num) 21 { 22 yield return pencil1; 23 } 24 } 25 } 26 }
调用代码:
PencilBox pb=new PencilBox();
foreach (Pencil p in pb.GetEnumerator(1))
{
Console.WriteLine(p.Color);
}