您好,登錄后才能下訂單哦!
yield return 語(yǔ)句返回集合的一個(gè)元素
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[] { "張飛", "關(guān)羽", "貝貝", "香香" }; /// <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">開(kāi)始索引</param> /// <param name="j">長(zhǎng)度</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(); } } }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。