当前位置: 首页 > article >正文

c# IEnumerable--扩展方法

namespace Linq
{

    /// <summary>
    /// IEnumerable可枚举类---可迭代类型
    /// IEnumerator枚举器
    /// 
    /// 只要实现了IEnumerable接口,就可以对他进行遍历
    /// yield关键词 他做了什么工作?他是一个迭代器,它相当于实现了IEnumerator枚举器
    /// </summary>
    class IEnumerableShow
    {
        public void Show()
        {
            int[] array = { 1, 2, 3, 4, 5, 6 };
            int i = 1;
            string str = "ANT编程";
            Student student = new Student { ID = 1 };
            foreach (var item in student)
            {
                Console.WriteLine(item);
            }

        }
    }

    class Student:IEnumerable
    {
        public int ID { get; set; }

        public IEnumerator GetEnumerator()
        {
            yield实现了IEnumerator接口
            //yield return "ANT编程1";
            //yield return "ANT编程2";
            //yield return "ANT编程3";
            string[] student = { "ANT编程1" , "ANT编程2" , "ANT编程3" };
            return new StudentEnumerator(student);
        }
    }

    internal class StudentEnumerator : IEnumerator
    {
        private string[] _student;
        int _position = -1;

        public StudentEnumerator(string[] student)
        {
            this._student = student;
        }

        public object Current
        {
            get
            {
                if (_position==-1)
                {
                    throw new InvalidOperationException ();
                }
                if (_position >= _student.Length)
                {
                    throw new InvalidOperationException();
                }
                return _student[_position];
            }
        }
        public bool MoveNext()//就是让我们把操作推进到下一个
        {
            if (_position<_student.Length-1)
            {
                _position++;
                return true;
            }
            else
            {
                return false;
            }
        }

        public void Reset()//重置
        {
            _position = -1;
        }
    }
}

如若不理解,思考list集合的遍历;


http://www.kler.cn/news/137099.html

相关文章:

  • 【Qt】控件——Qt多元素控件、常见的多元素控件、多元素控件的使用、List Widget、Table Widget、Tree Widget
  • 数据结构——顺序表的基本操作
  • Vehicle Spy3.9如何新建工程—总览
  • 软件工程的学习之详细绪论
  • Linux LVS详解
  • jmeter学习(6)逻辑控制器
  • SD-WAN技术:重新定义网络连接方式
  • less相关
  • 基于STC12C5A60S2系列1T 8051单片机的模数芯片ADC0832实现模数转换应用
  • 【开发流程】持续集成、持续交付、持续部署
  • Android 13.0 Launcher3仿ios长按app图标实现抖动动画开始拖拽停止动画
  • Hibernate查询的方法
  • 维基百科文章爬虫和聚类【二】:KMeans
  • py Selenium来启动多个浏览器窗口或标签页,并操作它们
  • 回顾以前的java
  • 泗博MODBUS转PROFINET网关助力电子天平与西门子PLC无缝对接
  • 679 - Dropping Balls (UVA)
  • vue3定时器的清除
  • (论文阅读51-57)图像描述3 53
  • 【django+vue】连接数据库、登录功能
  • java中stream常用api介绍
  • 鸿蒙原生应用/元服务开发-AGC分发如何配置版本信息(上)
  • Python try except 用法
  • Linux ps -ef|grep去除 grep --color=auto信息
  • windows对话框
  • 字节8年经验之谈 —— 10大自动化测试框架总结!