成都网站建设设计

将想法与焦点和您一起共享

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://chengdu.cdxwcx.cn/article/isghdh.html