开发者

Implementing of IEnumerable<T>

开发者 https://www.devze.com 2023-01-06 05:45 出处:网络
I have a code: public sealed class Sequence : IEnumerable<MyClass&g开发者_Python百科t; { List<MyClass> _elements;

I have a code:

    public sealed class Sequence : IEnumerable<MyClass&g开发者_Python百科t;
    {
        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
}

That code doesn't want to compile. It DOESNT want to compile. Using the generic type 'System.Collections.Generic.IEnumerator' requires '1' type arguments

Help me to rewrite MyClass to support enumeration.

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


Add the line:

using System.Collections;

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


Sounds like you're just missing a using directive, since IEnumerator (of the non-generic variety) lives in System.Collections, and not System.Collections.Generic (which is included by default at the top of every source file).

So just define:

using System.Collections;

ando you're good to go.

0

精彩评论

暂无评论...
验证码 换一张
取 消