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

后端 未结 10 1251
栀梦
栀梦 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:03

    In general, if you're trying to do this, you need to think long and hard about your design, because you're probably not using the best construction. In this case, the best answer would probably be

    string[] sArray = Enumerable.Repeat("Some assignment.\r\n", 5).ToArray();
    

    Higher level constructions are almost always usable instead of this kind of loop in C#. (And C++, but that's a whole other topic)

提交回复
热议问题