Playback Capturing an Iterative Variable

I reread the part from C # 5.0 to Nutshell about capturing iterative variables (Page 138), and I tried to reproduce the code below in C # 4.0 and C # 5.0, but not hoping to catch the difference so far

using System; class Test { static void Main() { Action[] actions = new Action[3]; int i = 0; foreach (char c in "abc") actions[i++] = () => Console.Write(c); for (int j = 0; j < 3; j++) { actions[j](); } foreach (Action a in actions) a(); Console.ReadLine(); } } 

Note I have Visual Studio 2012 (.net 4.0 and 4.5) and I changed the target structure trying to reproduce the problem.

Update to explain more problems, output from C # 4.0 will be different from C # 5.0
I know this might be less useful due to updating the latest version of C # Compiler

can someone enlighten me on how to reproduce this problem?

+2
source share
3 answers

You cannot play it because you are changing the version of the .Net framework, but not the compiler. You always use C # v5.0, which fixes the problem for foreach loops. You can see the problem with for loops:

 Action[] actions = new Action[3]; int i = 0; for (int j = 0; j < "abc".Length; j++) actions[i++] = () => Console.Write("abc"[j]); for (int j = 0; j < 3; j++) { actions[j](); } foreach (Action a in actions) a(); Console.ReadLine(); 

To use the old compiler, you need an old version of VS. In this case, to see your code break with foreach , you need to test it in VS 2010 (I did it locally).


You might want to try changing the language version of the compiler (as suggested by xanatos in the comments), but not using the old compiler. It uses the same compiler, but restricts the use of certain functions:

Because each version of the C # compiler contains extensions for the language specification, /langversion does not give you the equivalent functionality of an earlier version of the compiler.

From / langversion (C # compiler options)

+4
source

Since this problem has been fixed in the C # compiler 5.0, you cannot reproduce it with Visual Studio 2012.

You need to use the C # compiler version 4.0 to reproduce the problem that the author is trying to explain. With Visual Studio 2010, you can reproduce the problem.

Even if you change the language version in Vs2012, it still will not work. because you are still using the c # 5.0 compiler .

+3
source

This behavior has been changed for foreach loops since version 4.0. But you can reproduce it with a for loop:

 static void Main() { Action[] actions = new Action[3]; int i = 0; for (var c = 0; c < 3; c++) actions[i++] = () => Console.Write(c); for (int j = 0; j < 3; j++) { actions[j](); } foreach (Action a in actions) a(); Console.ReadLine(); } 

Exit: "333333"

0
source

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


All Articles