Is there a built-in way to convert IEnumerator to IEnumerable

前端 未结 8 1810
面向向阳花
面向向阳花 2020-12-30 18:55

Is there a built-in way to convert IEnumerator to IEnumerable?

8条回答
  •  长情又很酷
    2020-12-30 19:11

    The other answers here are ... strange. IEnumerable has just one method, GetEnumerator(). And an IEnumerable must implement IEnumerable, which also has just one method, GetEnumerator() (the difference being that one is generic on T and the other is not). So it should be clear how to turn an IEnumerator into an IEnumerable:

        // using modern expression-body syntax
        public class IEnumeratorToIEnumerable : IEnumerable
        {
            private readonly IEnumerator Enumerator;
    
            public IEnumeratorToIEnumerable(IEnumerator enumerator) =>
                Enumerator = enumerator;
    
            public IEnumerator GetEnumerator() => Enumerator;
            IEnumerator IEnumerable.GetEnumerator() => Enumerator;
        }
    
        foreach (var foo in new IEnumeratorToIEnumerable(fooEnumerator))
            DoSomethingWith(foo);
    
        // and you can also do:
    
        var fooEnumerable = new IEnumeratorToIEnumerable(fooEnumerator);
    
        foreach (var foo in fooEnumerable)
            DoSomethingWith(foo);
    
        // Some IEnumerators automatically repeat after MoveNext() returns false,
        // in which case this is a no-op, but generally it's required.
        fooEnumerator.Reset();
    
        foreach (var foo in fooEnumerable)
            DoSomethingElseWith(foo);
    

    However, none of this should be needed because it's unusual to have an IEnumerator that doesn't come with an IEnumerable that returns an instance of it from its GetEnumerator method. If you're writing your own IEnumerator, you should certainly provide the IEnumerable. And really it's the other way around ... an IEnumerator is intended to be a private class that iterates over instances of a public class that implements IEnumerable.

提交回复
热议问题