c# - How can I implement IEnumerator<T>? -
this code not compiling, , it's throwing following error:
the type 'testesinterfaces.mycollection' contains definition 'current'
but when delete ambiguous method, keeps giving other errors.
can help?
public class mycollection<t> : ienumerator<t> { private t[] vector = new t[1000]; private int actualindex; public void add(t elemento) { this.vector[vector.length] = elemento; } public bool movenext() { actualindex++; return (vector.length > actualindex); } public void reset() { actualindex = -1; } void idisposable.dispose() { } public object current { { return current; } } public t current { { try { t element = vector[actualindex]; return element; } catch (indexoutofrangeexception e) { throw new invalidoperationexception(e.message); } } } }
i think you're misunderstanding ienumerator<t>
. typically, collections implement ienumerable<t>
, not ienumerator<t>
. can think of them this:
- when class implements
ienumerable<t>
, stating "i collection of things can enumerated." - when class implements
ienumerator<t>
, stating "i thing enumerates on something."
it rare (and wrong) collection implement ienumerator<t>
. doing so, you're limiting collection single enumeration. if try loop through collection within segment of code that's looping through collection, or if try loop through collection on multiple threads simultaneously, won't able because collection storing state of enumeration operation. typically, collections (implementing ienumerable<t>
return separate object (implementing ienumerator<t>
) , separate object responsible storing state of enumeration operation. therefore, can have number of concurrent or nested enumerations because each enumeration operation represented distinct object.
also, in order foreach
statement work, object after in
keyword, must implement ienumerable
or ienumerable<t>
. not work if object implements ienumerator
or ienumerator<t>
.
i believe code you're looking for:
public class mycollection<t> : ienumerable<t> { private t[] vector = new t[1000]; private int count; public void add(t elemento) { this.vector[count++] = elemento; } public ienumerator<t> getenumerator() { return vector.take(count).getenumerator(); } ienumerator ienumerable.getenumerator() { return getenumerator(); } }
Comments
Post a Comment