Implement IEnumerable <T>

I have a code:

    public sealed class Sequence : IEnumerable<MyClass>
    {
        List<MyClass> _elements;

        public IEnumerator<MyClass> Getenumerator()
        {
            foreach (var item in _elements)
            {
                yield return item;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this._elements.GetEnumerator();
        }
    }


// ....

Sequence s = new Sequence();

// ...
// filling s with some data
// ...

foreach(MyClass c in s)
{
   // some action
}

This code does not want to compile. He does NOT want to compile. Using the generic type "System.Collections.Generic.IEnumerator" requires arguments of type "1"

Help me rewrite MyClass to support enumeration.

I tried several combinations, used Google. Everywhere examples Enumerable and IEnumerator without generics.

+3
source share
2 answers

Add a line:

using System.Collections;

You want to use System.Collections.IEnumerator, not System.Collections.Generic.IEnumerator<T>.

+3
source

, using, IEnumerator ( ) System.Collections, System.Collections.Generic ( ).

, :

using System.Collections;

.

0

Source: https://habr.com/ru/post/1753131/


All Articles