IEnumerator移回记录 [英] IEnumerator moving back to record

查看:52
本文介绍了IEnumerator移回记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,那就是我必须背靠背并且要加强记录.所以我正在使用IEnumerator.但是我可以通过movenext前进,但是没有办法退回

I have requirement in which I have to back and fort with record. So I am using IEnumerator to that. But I can move forward by movenext but there no way to move back

推荐答案

这是您可以通过将 IEnumerator< T> 的内容捕获在 List< T> <中来包装 IEnumerator< T> 的一种方法/code>:

Here's one way you could wrap an IEnumerator<T>, by capturing its contents in a List<T> as it moves along:

public interface ITwoWayEnumerator<T> : IEnumerator<T>
{
    bool MovePrevious();
}

public class TwoWayEnumerator<T> : ITwoWayEnumerator<T>
{
    private IEnumerator<T> _enumerator;
    private List<T> _buffer;
    private int _index;

    public TwoWayEnumerator(IEnumerator<T> enumerator)
    {
        if (enumerator == null)
            throw new ArgumentNullException("enumerator");

        _enumerator = enumerator;
        _buffer = new List<T>();
        _index = -1;
    }

    public bool MovePrevious()
    {
        if (_index <= 0)
        {
            return false;
        }

        --_index;
        return true;
    }

    public bool MoveNext()
    {
        if (_index < _buffer.Count - 1)
        {
            ++_index;
            return true;
        }

        if (_enumerator.MoveNext())
        {
            _buffer.Add(_enumerator.Current);
            ++_index;
            return true;
        }

        return false;
    }

    public T Current
    {
        get
        {
            if (_index < 0 || _index >= _buffer.Count)
                throw new InvalidOperationException();

            return _buffer[_index];
        }
    }

    public void Reset()
    {
        _enumerator.Reset();
        _buffer.Clear();
        _index = -1;
    }

    public void Dispose()
    {
        _enumerator.Dispose();
    }

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

然后我将使用扩展方法公开这种枚举器:

Then I would expose this kind of enumerator using an extension method:

public static class TwoWayEnumeratorHelper
{
    public static ITwoWayEnumerator<T> GetTwoWayEnumerator<T>(this IEnumerable<T> source)
    {
        if (source == null)
            throw new ArgumentNullExceptions("source");

        return new TwoWayEnumerator<T>(source.GetEnumerator());
    }
}

请注意,如果您要处理的集合已经是一个索引集合,例如 T [] List< T> ,那么这绝对是多余的.对于某些情况,例如当您枚举尚未以方便索引的形式进行排序的序列,并且希望能够向前和向后前进时,这种方法更有意义.

Note that this is definitely overkill if the collection you're dealing with is already an indexed collection such as a T[] or a List<T>. It makes more sense for scenarios such as when you're enumerating over a sequence that isn't already in a conveniently indexed form and you want to be able to go backwards as well as forwards.

这篇关于IEnumerator移回记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆