C#IEnumerable相当于java Iterator的next()方法?

时间:2015-04-27 12:45:37

标签: java c# iterator ienumerable

我发现(here)c#中的Iterator实现模仿Java的Iterator方法,但我不太确定如何在我的情况下使用它,或者是否有更简单的选项来重写此方法c#的方式。 原始java方法:

public RWIterator<T> search (T e){

    RWIterator<T> it =null;
    RWIterator<T> current = iterator();
    RWIterator<T> prev = iterator();
    boolean found=false;
    while(! found && current.hasNext()){
        T el=current.next();
        if (el.equals(e)) found = true;
        else prev.next();
    }
    if (found) {
        //Iterator<T> tmp = prev;
        //System.out.println("searched value is="+tmp.next());
        it = prev;
    }
    return it;
}

在RWIterator扩展java Iterator的地方,我无法理解prev的用法。我现在卡住了:

public RWIterator<T> Search(T e)
{

    RWIterator<T> it = null;
    RWIterator<T> current = Iterator();
    RWIterator<T> prev = Iterator();
    bool found = false;
    while (!found && current.GetEnumerator().MoveNext())
    {
        T el = current.GetEnumerator().Current;
        if (el.Equals(e)) found = true;
        else
        {
           //what should happen with prev.GetEnumerator().Current ?
        }
    }
    if (found)
    {
        //Iterator<T> tmp = prev;
        //System.out.println("searched value is="+tmp.next());
        it = prev;
    }
    return it;
}

3 个答案:

答案 0 :(得分:2)

您可以使用<a href="#">Link text</a>方法获取对Enumerator的引用,然后您可以使用GetEnumerator方法继续前进,并使用MoveNext属性访问你的元素:

Current

答案 1 :(得分:1)

好的Buddy,它接触你的搜索方法试图实现的是在整个迭代器中运行,直到找到匹配为止。然后它将从此匹配开始返回一个迭代器。这是您的方法的替代方案,可以实现我刚才描述的内容:

public RWIterator<T> Search(T e)
{
    RWIterator<T> myIterator = Iterator();
    bool found = false;
    foreach (T element in myIterator)
    {
        if (found)
            yield return element;
        else if (element.Equals(e))
        {
            found = true;
            yield return element;
        }
    }
}

答案 2 :(得分:0)

C#拥有foreach - 循环来访问IEnumerable。可以使用GetEnumerator访问每个具有foreach方法的对象。

我认为您不应该尝试直接将Java转换为C#,因为底层概念存在一些差异。你在Java中有Iterator的地方,你有IEnumerable - 在C#中的实现。然后使用foreach完成迭代。

public RWIterator<T> Search(T e)
{

    RWIterator<T> it = null;
    RWIterator<T> current = Iterator();
    RWIterator<T> prev = Iterator();
    bool found = false;
    // while (!found && current.GetEnumerator().MoveNext())
    foreach(T el in current)
    {
        // T el = current.GetEnumerator().Current;
        if (el.Equals(e)) found = true;
        else
        {
           //what should happen with prev.GetEnumerator().Current ?
        }
    }
    if (found)
    {
        //Iterator<T> tmp = prev;
        //System.out.println("searched value is="+tmp.next());
        it = prev;
    }
    return it;
}
相关问题