Reproduce Capturing iteration variable issue

前端 未结 3 964
时光取名叫无心
时光取名叫无心 2021-01-22 20:01

I\'m rereading a part from c# 5.0 in Nutshell about the capturing iteration variables (Page 138) and I have tried to reproduce the code bellow on c# 4.0 and c# 5.0 but with n

3条回答
  •  梦毁少年i
    2021-01-22 20:18

    You can't reproduce it because you are changing the version of the .Net framework but not the compiler. You're always using C# v5.0 which fixes the issue for foreach loops. You can see the issue with for loops though:

    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 VS version. In this case to see your code break with foreach you need to test it in VS 2010 (I did locally).


    You might want to try to change the language version of the compiler (as xanatos suggested in the comments) but that doesn't use an old compiler. It uses the same compiler but limits you to using specific features:

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

    From /langversion (C# Compiler Options)

提交回复
热议问题