Why can't I modify the loop variable in a foreach?

后端 未结 6 1590
孤城傲影
孤城傲影 2020-12-03 15:21

Why is a foreach loop a read only loop? What reasons are there for this?

6条回答
  •  醉话见心
    2020-12-03 16:13

    I'm not sure exactly what you mean by a "readonly loop" but I'm guessing that you want to know why this doesn't compile:

    int[] ints = { 1, 2, 3 };
    foreach (int x in ints)
    {
        x = 4;
    }
    

    The above code will give the following compile error:

    Cannot assign to 'x' because it is a 'foreach iteration variable'
    

    Why is this disallowed? Trying to assigning to it probably wouldn't do what you want - it wouldn't modify the contents of the original collection. This is because the variable x is not a reference to the elements in the list - it is a copy. To avoid people writing buggy code, the compiler disallows this.

提交回复
热议问题