Implement IEnumerator <T>

I have this code

public class SomeClass<T>: IEnumerable<T>
{
    public List<SomeClass<T>> MyList = new List<SomeClass<T>>();

    public IEnumerator<T> GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

How can I extract IEnumerator from MyList?

Thanks StackoverFlower ....

+3
source share
5 answers

It:

public List<SomeClass<T>> MyList = new List<SomeClass<T>>();

The following is required:

public List<T> MyList = new List<T>();

then this should work:

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

You cannot have

List<SomeClass<T>>

to which you pull the enumerator, because you specified in the interface that the enumerator will return an enumerated element <T>. You can also change IEnumerable<T>to

IEnumerable<SomeClass<T>>

and change the Enumerator to

public IEnumerator<SomeClass<T>> Getenumerator ()
{
  foreach (var item in MyList){
     yield return item;}
}
+8
source

A trivial option would be return MyList.GetEnumerator().

+1
source

- , - ( ). Trodek, :

Cannot implicitly convert type `System.Collections.Generic.List<SomeClass<T>>.Enumerator' to `System.Collections.Generic.IEnumerator<T>'(CS0029)

, . yield return, , . (, ), , , .

, !

+1

, T SomeClass,

public IEnumerator<T> GetEnumerator()
{
    return MyList.Select(ml => ml.GetT() /* operation to get T */).GetEnumerator();
}
+1

,

MyNamespace.MyClass<T>' does not implement interface
  member 'System.Collections.IEnumerable.GetEnumerator()'.
  'WindowsFormsApplication1.SomeClass<T>.GetEnumerator()' cannot implement
  'System.Collections.IEnumerable.GetEnumerator()' because it does not have
  the matching return type of 'System.Collections.IEnumerator'.

GetEnumerator():

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

IEnumerable<T> IEnumerable, GetEnumerator().

0

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


All Articles