What is the difference between and foreach regarding closure

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 forandforeach

there are some differences
var 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());

//will throw exception
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 forand foreachin closures?

+4
source share
1 answer

, #. , # 5, . :

# 5 foreach , .

# 5 same. , , .

# 5, new. , , , .

+6

Source: https://habr.com/ru/post/1612733/


All Articles