为什么赋值运算符 (=) 在 foreach 循环中无效? [英] Why are assignment operators (=) invalid in a foreach loop?

查看:25
本文介绍了为什么赋值运算符 (=) 在 foreach 循环中无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么赋值运算符 (=) 在 foreach 循环中无效?我使用的是 C#,但我认为该参数对于支持 foreach 的其他语言(例如 PHP)是相同的.例如,如果我做这样的事情:

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 foreach (e.g. PHP). For example, if I do something like this:

string[] sArray = new string[5];

foreach (string item in sArray)
{
   item = "Some assignment.
";
}

我收到一个错误,无法分配给‘item’,因为它是一个‘foreach迭代变量’."

I get an error, "Cannot assign to 'item' because it is a 'foreach iteration variable'."

推荐答案

这是你的代码:

foreach (string item in sArray)
{
   item = "Some assignment.
";
}

这里是 粗略估计 编译器对此做了什么:

Here's a rough approximation of what the compiler does with this:

using (var enumerator = sArray.GetEnumerator())
{
    string item;
    while (enumerator.MoveNext())
    {
        item = enumerator.Current;

        // Your code gets put here
    }
}

IEnumerator.Current 属性是只读的,但这实际上与此处无关,因为您正在尝试将本地 item 变量分配给新的价值.阻止您这样做的编译时检查基本上是为了保护您免于做一些不会像您期望的那样工作的事情(即,更改局部变量并且对底层集合/序列没有影响).

The IEnumerator<T>.Current property is read-only, but that's not actually relevant here, as you are attempting to assign the local item variable to a new value. The compile-time check preventing you from doing so is in place basically to protect you from doing something that isn't going to work like you expect (i.e., changing a local variable and having no effect on the underlying collection/sequence).

如果您想在枚举时修改索引集合的内部结构,例如 string[],传统的方法是使用 for 循环而不是 <代码>foreach:

If you want to modify the internals of an indexed collection such as a string[] while enumerating, the traditional way is to use a for loop instead of a foreach:

for (int i = 0; i < sArray.Length; ++i)
{
    sArray[i] = "Some assignment.
";
}

这篇关于为什么赋值运算符 (=) 在 foreach 循环中无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆