IEnumerator<T> Implementation
I have a 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 c开发者_如何学运维an I Extract a IEnumerator from MyList ?
Thanks StackoverFlower....
This:
public List<SomeClass<T>> MyList = new List<SomeClass<T>>();
Needs to be this:
public List<T> MyList = new List<T>();
then, this should work:
public IEnumerator<T> Getenumerator ()
{
foreach (var item in MyList){
yield return item;}
}
You can't have a
List<SomeClass<T>>
that you pull the enumerator for, because you have specified in the interface that the enumerator will return an enumerable item of <T>
. You can also change IEnumerable<T>
to be
IEnumerable<SomeClass<T>>
and change the Enumerator to be
public IEnumerator<SomeClass<T>> Getenumerator ()
{
foreach (var item in MyList){
yield return item;}
}
The trivial option would be return MyList.GetEnumerator()
.
Kevins answer is the correct and is lazy (even better). If you use Trodek response the following exception will be throw:
Cannot implicitly convert type `System.Collections.Generic.List<SomeClass<T>>.Enumerator' to `System.Collections.Generic.IEnumerator<T>'(CS0029)
Nevertheless I want to add a comment. When you use yield return a state machine is generated which will be returning the different values. If you are going to use nested data structures (trees for example) using yield return will be allocating far more memory because a different state machine will be created in every sub structure.
Well, those are my two cents!
Assuming there is a way to get an object T out of an object SomeClass,
public IEnumerator<T> GetEnumerator()
{
return MyList.Select(ml => ml.GetT() /* operation to get T */).GetEnumerator();
}
As an add on to the accepted answer, if you received the message
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'.
You need to implement the additional GetEnumerator()
method:
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
IEnumerable<T>
implements IEnumerable
so both forms of GetEnumerator()
must be implemented.
精彩评论