c# - Strange behavior of Enumerator.MoveNext() -
could explain why code running in infinity loop? why movenext() return true always?
var x = new { templist = new list<int> { 1, 3, 6, 9 }.getenumerator() }; while (x.templist.movenext()) { console.writeline("hello world"); }
list<t>.getenumerator() returns mutable value type (list<t>.enumerator). you're storing value in anonymous type.
now, let's have @ does:
while (x.templist.movenext()) { // ignore } that's equivalent to:
while (true) { var tmp = x.templist; var result = tmp.movenext(); if (!result) { break; } // original loop body } now note we're calling movenext() on - copy of value in anonymous type. can't change value in anonymous type - you've got property can call, give copy of value.
if change code to:
var x = new { templist = (ienumerable<int>) new list<int> { 1, 3, 6, 9 }.getenumerator() }; ... you'll end getting reference in anonymous type. reference box containing mutable value. when call movenext() on reference, value inside box mutated, it'll want.
for analysis on similar situation (again using list<t>.getenumerator()) see my 2010 blog post "iterate, damn you!".
Comments
Post a Comment