您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。