C#枚举器和迭代器

文章不定时更新,有问题的话欢迎各位dalao指正。

枚举器与可枚举类型

foreach:
我们可以通过foreach来便历或取出数组中的每一个元素:

int[] arr1 = {
   
    10, 11, 12, 13 };
foreach(int item in arr1)
{
   
   
    Console.WriteLine($"value:{
     
     item}");
}

输出:

value:10
value:11
value:12
value:13

foreach中in后面跟的参数必须是可枚举类型(enumerable type)。
可枚举类型是实现了GetEnumerator方法的类型,而GetEnumerator方法是获取对象枚举器的方法,对于枚举器而言,必须有个方法去获取他。

IEnumerator和IEnumerable

1、IEnumerator

namespace System.Collections
{
   
   
    //
    // 摘要:
    //     Supports a simple iteration over a non-generic collection.
    public interface IEnumerator
    {
   
   
        //
        // 摘要:
        //     Gets the element in the collection at the current position of the enumerator.
        //
        // 返回结果:
        //     The element in the collection at the current position of the enumerator.
        object? Current {
   
    get; }

        //
        // 摘要:
        //     Advances the enumerator to the next element of the collection.
        //
        // 返回结果:
        //     true if the enumerator was successfully advanced to the next element; false if
        //     the enumerator has passed the end of the collection.
        //
        // 异常:
        //   T:System.InvalidOperationException:
        //     The collection was modified after the enumerator was created.
        bool MoveNext();
        //
        // 摘要:
        //     Sets the enumerator to its initial position, which is before the first element
        //     in the collection.
        //
        // 异常:
        //   T:System.InvalidOperationException:
        //     The collection was modified after the enumerator was created.
        void Reset();
    }
}


Current、MoveNext()、Reset是枚举器的三个成员
Current只读,获取集合中枚举器当前位置的元素
MoveNext()将枚举器前进到集合的下一个元素。
Reset()将枚举数设置为其初始位置,即集合中第一个元素之前的位置(-1)。

其实在我们使用foreach语句的时候,C#编译器会生成和下面非常相似的代码。

int[] arr1 = {
   
    10, 11, 12, 13 };
IEnumerator ie = arr1.GetEnumerator();
while (ie.MoveNext())//移到下一项
{
   
   
    int i = (int)ie.Current;//获取当前项
    Console.WriteLine($"{
     
     i}");
}

10
11
12
13

2、IEnumerable

实现了IEnumerable接口的类叫做可枚举类。
IEnumerable接口中的GetEnumerator 方法返回对象的枚举器。
声明:

class MyClass : IEnumerable//实现IEnumerable接口
{
   
   
    public IEnumerator GetEnumerator() {
   
   
        //函数返回IEnumerator类型的对象
    }
}

使用IEnumerator和IEnumerable的示例:

class ColorEnumerator 
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值