C# 迭代器

yield return 的核心逻辑和继承两个接口实现其中的方法是一样的

迭代器是一种设计模式

yield return 只需要继承一个IEnumerable接口

1.先获取in后面这个对象的 IEnumerator,会调用对象其中的GetEnumerator方法 来获取

2.执行得到这个IEnumerator对象中的 MoveNext方法

3.只要MoveNext方法的返回值时true 就会去得到Current,然后复制给 item

cs 复制代码
using System.Collections;
using System.Reflection;

class Program
{
    public static void Main()
    {
        Mylist alist = new Mylist();
        foreach (var item in alist)
        {
            Console.WriteLine(item);
        }
    }
}
class Mylist:IEnumerable,IEnumerator
{
    char[] charArray;
   int Cursor = -1;
    
    public Mylist() 
    {
        charArray = new char[] {'a','b','c','d','e'};
       
    }

    //public IEnumerator GetEnumerator()
    //{
    //    for (int i = 0; i < charArray.Length; i++)
    //    {
    //        yield return charArray[i];
    //    }
    //}


    public object Current 
    {
        get
        {
            return charArray[Cursor];
        }
    }
    public IEnumerator GetEnumerator()
    {
        Reset();
       return this;
    }

    public bool MoveNext()
    {
        Cursor++;
        return (Cursor < charArray.Length);
    }

    public void Reset()
    {
        Cursor = -1;
    }
}
相关推荐
郑州光合科技余经理3 小时前
本地生活服务系统:成品模块和定制接口怎么划界
java·前端·人工智能·后端·系统架构·php·ai编程
anlog7 小时前
ini文件读取,EXE同目录文件读取
c#·ini
平头哥~7 小时前
Day 07 _ 那条 1px 的线,为什么在手机上忽粗忽细
前端·css·样式·学习资料
rockey6277 小时前
AScript之编译递归函数
c#·.net·script·动态脚本
小江的记录本7 小时前
【CSS】CSS 动画:transition、animation、transform、CSS3 新特性(附《思维导图》)
前端·css·安全·spring·前端框架·css3·动画
circuitsosk7 小时前
任务规划器的三种范式对比:ReAct、Plan-and-Execute 与 Tree-of-Thought 在真实业务中的取舍
前端·javascript·python·react.js·llm·ai agent
倔强的石头_8 小时前
连接数失控排查:从数据库会话、应用线程池到连接池泄漏
数据库
hzxpaipai9 小时前
企业官网技术架构拆解:前端、后台、数据库、服务器如何协同
前端·数据库·架构
爱吃火鸡面呀10 小时前
MySQL DQL 子查询详解:从标量、列、行到表子查询的完整实战
大数据·数据库·mysql
harmony&10 小时前
OpenStack 云平台管理实战:从 Keystone 认证到 Nova 计算调度
数据库·openstack