Why does this C # program output such a result? How do I understand the closure?

I tried to understand the answer to this question. Why am I getting the wrong results when I call Func <int>? I wrote some code examples. Following code

public static void Main(string[] args)
{
    var funcs = new List<Func<string>>();
    for(int v=0,i=0;v<3;v++,i++)
    {
        funcs.Add( new Func<string>(delegate(){return "Hello "+ i++ +" "+v;}) );
    }
    foreach(var f in funcs)
        Console.WriteLine(f());
}

produces

Hello 3 3
Hello 4 3
Hello 5 3

After reading the explanation of John Skeet and Eric Lippert, I thought I would get

Hello 3 3
Hello 3 3
Hello 3 3

Here both v and i are loop variables, while the value i is matched at this moment v, and not why is this ?. I do not understand the behavior.

+5
source share
4 answers

Well, you understood Eric and John correctly, but you missed one part of your code:

"Hello "+ i++ +" "+v;
          ^^^
          this part increments i for each call

So basically, what happens is like this:

  • 3 , ,
  • 3
  • , i v, i
  • , i v, i, , 4 , 3
  • ..

, , , , :

for(int v=0,i=0;v<3;v++,i++)
{
    int ii = i, vv = v;
    funcs.Add( new Func<string>(delegate(){return "Hello "+ ii++ +" "+vv;}) );
}

0, 0, 1, 1 2, 2. ii, , ( .) Thanks @ferosekhanj

+11

: ++i , . 3, .
, for, foreach.

+2

( ?;)) , v.

v , v == 3 . == 3 . , (i ++). , , , v.

, .

+2

, for.

public static void Main(string[] args)
{
    var funcs = new List<Func<string>>();
    int i=0;
    for(int v=0;v<3;v++,i++)
    {
        funcs.Add( new Func<string>(delegate(){return "Hello "+ i++ +" "+v;}) );
    }
    foreach(var f in funcs)
        Console.WriteLine(f());
}

for i==3 v==3. i , i. , i, 3, 4, 5

0

All Articles