yield return 语句返回集合的一个元素
yield break 可停止迭代
------------------------------------------------------------------Student.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication3 { public class Student { string[] str = new string[] { "张飞", "关羽", "贝贝", "香香" }; /// <summary> /// 正序迭代 /// </summary> /// <returns></returns> public IEnumerator<string> GetEnumerator() { for (int i = 0; i < str.Length; i++) { yield return str[i]; } } /// <summary> /// 倒序迭代 /// </summary> /// <returns></returns> public IEnumerable<string> Reverse() { for (int i = str.Length-1; i >= 0; i--) { yield return str[i]; } } /// <summary> /// 自定义迭代 /// </summary> /// <param name="i">开始索引</param> /// <param name="j">长度</param> /// <returns></returns> public IEnumerable<string> Subset(int index, int length) { for (int i = index; i < index+length; i++) { yield return str[i]; } } } }
------------------------------------------------------------------主程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { Student s = new Student(); foreach (var item in s)//正序迭代 { Console.WriteLine(item); } Console.WriteLine("reverse"); foreach (var item in s.Reverse())//倒序迭代 { Console.WriteLine(item); } Console.WriteLine("subset");//自定义迭代 foreach (var item in s.Subset(1,1)) { Console.WriteLine(item); } Console.ReadKey(); } } }
本文出自 “程序猿的家” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1528479
原文地址:http://962410314.blog.51cto.com/7563109/1528479