资讯

精准传达 • 有效沟通

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

yield---迭代集合的不同方式-创新互联

yield return 语句返回集合的一个元素

五峰ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18982081108(备注:SSL证书合作)期待与您的合作!

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();
        }
    }
}

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。


网站标题:yield---迭代集合的不同方式-创新互联
网站路径:http://cdkjz.cn/article/dopiej.html
多年建站经验

多一份参考,总有益处

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

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

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