您好,登錄后才能下訂單哦!
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(); } } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。