资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

yield---迭代集合的不同方式

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[] { "张飞", "关羽", "贝贝", "香香" };
        /// 
        /// 正序迭代
        /// 
        /// 
        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < str.Length; i++)
            {
                yield return str[i];
            }
        }
        /// 
        /// 倒序迭代
        /// 
        /// 
        public IEnumerable Reverse()
        {
            for (int i = str.Length-1; i >= 0; i--)
            {
                yield return str[i];
            }
        }
        /// 
        /// 自定义迭代
        /// 
        /// 开始索引
        /// 长度
        /// 
        public IEnumerable 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();
        }
    }
}

名称栏目:yield---迭代集合的不同方式
链接分享:http://cdkjz.cn/article/isghdh.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220