//迭代器是延迟计算的,用foreach时,自动调用MoveNext时调用 private static IEnumerable <string> WhereListWithIterator(FriendColl ff) { for (var i = 0; i < ff.Count; i++) { yield return(ff[i].Name); } }
private static void ChildTest1() { FriendColl friends = new FriendColl(); friends[1] = new Friend("fwq"); friends.Add(new Friend("zxc", 100)); foreach (Friend f in friends) { Console.WriteLine(f.Name + " " + f.Age); } Console.WriteLine("---------------------------------------------"); Console.WriteLine("使用yield return 返回一个枚举序列"); foreach (int ii in WithIterator()) { Console.WriteLine(ii); } var tempList = WhereListWithIterator(friends); foreach (var ss in tempList) { Console.WriteLine(ss); } Console.ReadKey(); }
private Friend current; //当前指向的元素 internal FriendCollIterator(FriendColl fcol) { friends = fcol; index = 0; }