Why are assignment operators (=) invalid in a foreach loop?

后端 未结 10 1191
栀梦
栀梦 2020-12-14 07:10

Why are assignment operators (=) invalid in a foreach loop? I\'m using C#, but I would assume that the argument is the same for other languages that support

相关标签:
10条回答
  • 2020-12-14 08:06

    Because the language specification says so.

    But seriously, not all sequences are arrays or things that can be logically modified or written to. For instance:

    foreach (var i in Enumerable.Range(1, 100)) {
       // modification of `i` will not make much sense here.
    }
    

    While it would've been technically possible to have i = something; modify a local variable, it can be misleading (you may think it really changes something under the hood and it wouldn't be the case).

    To support these kind of sequences, IEnumerable<T> doesn't require a set accessor for its Current property, making it read-only. Thus, foreach cannot modify the underlying collection (if one exists) using the Current property.

    0 讨论(0)
  • 2020-12-14 08:07

    The foreach loop is designed to iterate through objects in a collection, not to assign things- it's simply design of the language.

    Also, from MSDN:

    "This error occurs when an assignment to variable occurs in a read- only context. Read-only contexts include foreach iteration variables, using variables, and fixed variables. To resolve this error, avoid assignments to a statement variable in using blocks, foreach statements, and fixed statements."

    The foreach keyword just enumerates IEnumerable instances (getting an IEnumerator instances by calling the GetEnumerator() method). IEnumerator is read-only, therefore values can't be changed using IEnumerator =can't be changed using the foreach context.

    0 讨论(0)
  • 2020-12-14 08:10

    You cannot modify an array that you are foreach'ing through. Use The following code instead:

    string[] sArray = new string[5]; 
    
    for (int i=0;i<sArray.Length;i++)
    {
        item[i] = "Some Assignment.\r\n";
    }
    
    0 讨论(0)
  • 2020-12-14 08:12

    The foreach is designed to interate through the array once, without repeating or skipping (though you can skip some action within the foreach construct by using the continue keyword). If you want to modify the current item, consider using a for loop instead.

    0 讨论(0)
提交回复
热议问题