The demo code has some problems.
var values = new List<int>() { 100, 110, 120 };
var funcs = new List<Func<int>>();
foreach(var v in values)
funcs.Add( ()=>v );
foreach(var f in funcs)
Console.WriteLine(f());
Most people expect this to be 100/110/120. In fact, it is 120/120/120.
but the result of vs2015 and .net 4.5.1 will be output 100/110/120, not 120/120/120 .
And when I test the code as follows, between for
andforeach
there are some differencesvar values = new List<int> {100, 110, 120};
var funcs = new List<Func<int>>();
foreach (var v in values)
funcs.Add(() =>
{
Console.WriteLine(v);
return v;
} );
foreach (var f in funcs)
Console.WriteLine(f());
for (int i=0;i<values.Count;i++)
funcs.Add(() =>
{
Console.WriteLine(values[i]);
return values[i];
});
foreach (var f in funcs)
Console.WriteLine(f());
Who can give me more information between for
and foreach
in closures
?
source
share