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

在C#中实现双向枚举器

在C#中,双向枚举器是一种可以在双向(前后)遍历集合的枚举器。在C#中,可以使用IEnumerator<T>接口来实现双向枚举器。

以下是一个简单的双向枚举器示例:

代码语言:csharp
复制
public class BiDirectionalEnumerator<T> : IEnumerator<T>
{
    private readonly List<T> _items;
    private int _currentIndex;
    private readonly int _startIndex;

    public BiDirectionalEnumerator(List<T> items, int startIndex)
    {
        _items = items;
        _currentIndex = startIndex;
        _startIndex = startIndex;
    }

    public bool MoveNext()
    {
        if (_currentIndex < _items.Count - 1)
        {
            _currentIndex++;
            return true;
        }
        return false;
    }

    public bool MovePrevious()
    {
        if (_currentIndex > 0)
        {
            _currentIndex--;
            return true;
        }
        return false;
    }

    public void Reset()
    {
        _currentIndex = _startIndex;
    }

    public T Current
    {
        get { return _items[_currentIndex]; }
    }

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

    public void Dispose()
    {
    }
}

在这个示例中,我们定义了一个泛型的双向枚举器BiDirectionalEnumerator<T>,它实现了IEnumerator<T>接口,并添加了MovePrevious()方法来实现双向遍历。

使用这个双向枚举器的示例代码如下:

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

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

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

在这个示例中,我们创建了一个包含5个整数的列表,并使用BiDirectionalEnumerator<T>来遍历这个列表。首先,我们使用MoveNext()方法来遍历列表中的每个元素,然后再使用MovePrevious()方法来遍历列表中的每个元素。

需要注意的是,在使用双向枚举器时,必须确保在调用MovePrevious()方法之前已经调用了MoveNext()方法,否则MovePrevious()方法将返回false。同样地,在使用MoveNext()方法之前必须先调用MovePrevious()方法,否则MoveNext()方法将返回false

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

相关·内容

领券