C#学习相关系列之自定义遍历器

在C#中,自定义遍历器需要实现IEnumerable接口和IEnumerator接口。其中,IEnumerable接口包含一个GetEnumerator方法,该方法返回一个IEnumerator接口的实例,而IEnumerator接口包含Current、MoveNext和Reset方法。

IEnumerable:IEnumerable是一个接口,它代表一个可以迭代的集合。这意味着可以使用IEnumerator:foreach循环遍历IEnumerable对象中的元素。

在C#中,IEnumerator是.NET框架中的一个接口,它用于在集合中遍历元素。这个接口通常与使用foreach循环来遍历集合的代码一起使用。

IEnumerator接口定义了两个主要的方法:MoveNext()Reset()

  • MoveNext()方法用于将迭代器移动到集合中的下一个元素。如果集合中没有更多的元素,则该方法将返回false
  • Reset()方法用于重置迭代器,使其重新回到集合的起始位置。

此外,IEnumerator接口还定义了一个Current属性,它返回当前迭代器位置的元素。

一、yield关键字生成迭代器

cs 复制代码
using System;  
using System.Collections.Generic;  
  
class Program  
{  
    static void Main()  
    {  
        foreach (int number in GetNumbers())  
        {  
            Console.WriteLine(number);  
        }  
    }  
  
    static IEnumerable<int> GetNumbers()  
    {  
        for (int i = 0; i < 10; i++)  
        {  
            yield return i;  
        }  
    }  
}

只有IEnumerable才能通过foreach被遍历。

二、关于**IEnumerator的用法示例**

cs 复制代码
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };  
  
IEnumerator enumerator = fruits.GetEnumerator();  
  
while (enumerator.MoveNext())  
{  
    string fruit = (string)enumerator.Current;  
    Console.WriteLine(fruit);  
}

通过这个例子可以看出来 IEnumerable是一个可以迭代的集合,而**IEnumerator是定义foreach迭代器。**

三、自定义一可以遍历的类

cs 复制代码
 public class Program
    {
        static void Main(string[] args)
        {
            student st = new student();
            st.add(2);
            st.add(3);
            st.add(100);
            foreach (var item in st)
            {
                Console.WriteLine(item);
            }
            Console.Read();
        }
    }
    public class student : IEnumerable, IEnumerator

    {
        private List<int> _data;
        private int position = -1;
        private List<int> data = new List<int>();
        public student()
        { 
        }
        public student(List<int> data)
        {
            this._data = data;
        }

        public object Current => _data[position];

        public void add(int num)
        {
            data.Add(num);
        }
        public IEnumerator GetEnumerator()
        {
            return new student(data);
        }

        public bool MoveNext()
        {
            position++;
            return position < _data.Count;
        }

        public void Reset()
        {
            position = -1;
        }
    }

代码2

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

public class MyList : IEnumerable
{
    private int[] data = { 1, 2, 3, 4, 5 };

    public IEnumerator GetEnumerator()
    {
        return new MyEnumerator(data);
    }
}

public class MyEnumerator : IEnumerator
{
    private int[] data;
    private int position = -1;

    public MyEnumerator(int[] data)
    {
        this.data = data;
    }

    public object Current
    {
        get
        {
            return data[position];
        }
    }

    public bool MoveNext()
    {
        position++;
        return (position < data.Length);
    }

    public void Reset()
    {
        position = -1;
    }
}

// 使用自定义遍历器
class Program
{
    static void Main(string[] args)
    {
        MyList list = new MyList();
        foreach (int i in list)
        {
            Console.WriteLine(i);
        }
    }
}
相关推荐
lly202406几秒前
Swift 析构过程
开发语言
南境十里·墨染春水2 分钟前
linux学习进展 进程
linux·运维·学习
mu_guang_3 分钟前
计算机体系结构3-cache一致性和内存一致性的区别
java·开发语言·计算机体系结构
sp_fyf_20244 分钟前
【大语言模型】 语言模型学习什么以及何时学习?隐式课程假说
人工智能·学习·语言模型
星辰即远方5 分钟前
UI学习2
学习·ui
lingggggaaaa8 分钟前
PHP模型开发篇&MVC层&动态调试未授权&脆弱鉴权&未引用&错误逻辑
开发语言·安全·web安全·网络安全·php·mvc·代码审计
星原望野9 分钟前
java:volatile关键字的作用
java·开发语言·volatile
APIshop14 分钟前
Java获取淘宝商品价格、图片与视频:淘宝开放平台API实战指南
开发语言·python
William_cl15 分钟前
C# ASP.NET 分层架构实战:BLL (Service) 业务层从入门到封神(规范 + 避坑)
架构·c#·asp.net
XiYang-DING16 分钟前
【Java】Map和Set
java·开发语言