Sunday, 15 March 2015

c# - Confused about IEnumerator interface -



c# - Confused about IEnumerator interface -

i trying understand how utilize ienumerator interface , used for. have class implements ienumerator interface. string array passed constructor method.

the problem when execute code array not listed properly. should doing in order "ali", "veli", "hatca" it’s listed @ console in order "veli", "hatca" , -1. confused. doing wrong here? can please help?

static void main(string[] args) { ogr o = new ogr(); while (o.movenext()) { console.writeline(o.current.tostring()); } } public class ogr: ienumerator { arraylist array_ = new arraylist(); string[] names = new string[] { "ali", "veli", "hatca" }; public ogr() { array_.addrange(names); } public void addogr(string name) { array_.add(name); } int position; public object current { { if (position >= 0 && position < array_.count) { homecoming array_[position]; } else { homecoming -1; } } } public bool movenext() { if (position < array_.count && position >= 0) { position++; homecoming true; } else { homecoming false; } } public void reset() { position = 0; } }

ienumerator quite hard grasp @ first, luckily it's interface hardly ever utilize in itself. instead, should implement ienumerable<t>.

however, source of confusion comes line ienumerator documentation:

initially, enumerator positioned before first element in collection. reset method brings enumerator position. after enumerator created or reset method called, must phone call movenext method advance enumerator first element of collection before reading value of current; otherwise, current undefined.

your implementation has current position @ 0 initially, instead of -1, causing unusual behavior. enumerator begins current on first element instead of beingness before it.

c#

No comments:

Post a Comment