无法分配给项目,因为它是一个foreach迭代变量 [英] Cannot assign to item because it is a foreach iteration variable

查看:599
本文介绍了无法分配给项目,因为它是一个foreach迭代变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能在foreach循环中为局部变量赋值?

Why can't we assign a value to the local variable in a foreach loop?

我知道这不会更新集合,因为我们只是在更改局部变量引用的对象.

I understand this would not update the collection because we are just changing what object the local variable refers to.

如果使用while循环实现相同的功能,则可以更新局部变量.

If you implement the same functionality using a while loop, it allows you to update the local variable.

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> enumerable = new List<string> { "a", "b", "c" };

        //This foreach loop does not compile:
        foreach (string item in enumerable)
        {
            item = "d"; //"cannot assign to item because it is a foreach iteration variable"
        }

        //The equivalent C# code does compile and allows assinging a value to item:            
        var enumerator = enumerable.GetEnumerator();
        try
        {
            while (enumerator.MoveNext())
            {
                string item = (string)enumerator.Current;
                item = "d";
            }
        }
        finally
        {
            enumerator.Dispose();
        }
    }
}

这个问题与可能的重复问题不同,因为它问为什么在幕后它只是一个局部变量,它指向与enumerator.Current相同的对象,为什么我们不能修改迭代变量.

This question is different to the possible duplicate because it's asking why we can't modify the iteration variable when behind the scenes it's just a local variable pointing to the same object as enumerator.Current.

推荐答案

根据埃里克·利珀特(Eric Lippert)的

According to Eric Lippert's answer, The iteration variable is read-only because it is an error to write to it.

看起来编译器中有一些规则使您无法编译试图修改迭代变量的代码,即使该代码未在幕后标记为readonly(也不能因为它是局部变量而无法标记)

Looks like there is some rule in the compiler that stops you from compiling code that attempts to modify the iteration variable, even though it's not marked as readonly behind the scenes (it can't anyway because it's a local var).

这篇关于无法分配给项目,因为它是一个foreach迭代变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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