首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用迭代器编写自定义IEnumerator <T>

在这个问答内容中,我们要求您创建一个自定义的IEnumerator <T>迭代器。IEnumerator <T>是一个接口,用于实现在一系列元素上进行迭代。在这个例子中,我们将创建一个自定义的IEnumerator <T>,用于迭代一个泛型列表。

以下是一个简单的自定义IEnumerator <T>的实现:

代码语言:csharp
复制
using System;
using System.Collections;
using System.Collections.Generic;

public class CustomEnumerator<T> : IEnumerator<T>
{
    private readonly List<T> _items;
    private int _currentIndex;

    public CustomEnumerator(List<T> items)
    {
        _items = items;
        _currentIndex = -1;
    }

    public bool MoveNext()
    {
        _currentIndex++;
        return _currentIndex < _items.Count;
    }

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

    public T Current
    {
        get
        {
            if (_currentIndex < 0 || _currentIndex >= _items.Count)
            {
                throw new InvalidOperationException("Enumerator is in an invalid state.");
            }

            return _items[_currentIndex];
        }
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

    public void Dispose()
    {
        // No disposal needed in this example.
    }
}

在这个实现中,我们首先定义了一个泛型列表_items,用于存储我们要迭代的元素。我们还定义了一个_currentIndex变量,用于跟踪当前迭代的位置。

MoveNext()方法将_currentIndex递增,并检查是否已经到达列表的末尾。如果是,则返回false,表示迭代已完成。否则,返回true,表示迭代可以继续。

Reset()方法将_currentIndex重置为-1,以便从头开始迭代。

Current属性返回当前迭代的元素。如果_currentIndex超出范围,则抛出InvalidOperationException异常。

最后,Dispose()方法在这个简单的实现中不需要,因为我们没有分配任何资源。

您可以使用此自定义IEnumerator <T>迭代器来迭代任何泛型列表。例如:

代码语言:csharp
复制
var items = new List<int> { 1, 2, 3, 4, 5 };
var enumerator = new CustomEnumerator<int>(items);

while (enumerator.MoveNext())
{
    Console.WriteLine(enumerator.Current);
}

这将输出:

代码语言:txt
复制
1
2
3
4
5

请注意,这个答案中没有提及任何云计算品牌商,因为这个问题是关于IEnumerator <T>迭代器的实现的。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

扫码

添加站长 进交流群

领取专属 10元无门槛券

手把手带您无忧上云

扫码加入开发者社群

相关资讯

热门标签

活动推荐

    运营活动

    活动名称
    广告关闭
    领券