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

后端 未结 6 1577
孤城傲影
孤城傲影 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:05

    I would assume it's how the iterator travels through the list.

    Say you have a sorted list:

    Alaska
    Nebraska
    Ohio
    

    In the middle of

    foreach(var s in States)
    {
    }
    

    You do a States.Add("Missouri")

    How do you handle that? Do you then jump to Missouri even if you're already past that index.

提交回复
热议问题