I would like to implement a generic IEnumerator<T> extension method that returns the next element in the IEnumerable as followed:

var list = new List<MyClass>();
var enumerator = list.GetEnumerator();

var nextItem1 = enumerator.GetNext();
var nextItem2 = enumerator.GetNext();

// Instead of calling enumerator.MoveNext() and then reading the current item.

I tried to do this but it won't compile:

public static T GetNext(this IEnumerator<T> list)
{
     list.MoveNext();
     return list.Current;
}

Where did I go wrong? Thanks.

有帮助吗?

解决方案

You appear to be missing the generic type definition on the method signature:

public static T GetNext<T>(this IEnumerator<T> list)
{
    // ---- this bit---^^^
}

It needs to be there assuming there is no class level generic type with the same name. Otherwise it looks fine.

However...

I personally wouldn't do it this way as you are not listening to the result of MoveNext. Unless you can make assumptions about the expected values, there is no way for you to tell if the iterator reached the end of the set. For most common uses, this won't be a viable approach.

I actually went the other route and implemented an AsEnumerable extension method that simply iterates manually, but from the outside allows you to do stuff like foreach (var item in iterator.AsEnumerable()) and doesn't ignore the MoveNext result:

public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerator<TSource> iterator)
{
    while (iterator.MoveNext())
    {
        yield return iterator.Current;
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top