为什么我们不能分配 foreach 迭代变量,而我们可以使用访问器完全修改它? [英] Why can't we assign a foreach iteration variable, whereas we can completely modify it with an accessor?

查看:19
本文介绍了为什么我们不能分配 foreach 迭代变量,而我们可以使用访问器完全修改它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是对此感到好奇:以下代码将无法编译,因为我们无法修改 foreach 迭代变量:

I was just curious about this: the following code will not compile, because we cannot modify a foreach iteration variable:

        foreach (var item in MyObjectList)
        {
            item = Value;
        }

但以下将编译并运行:

        foreach (var item in MyObjectList)
        {
            item.Value = Value;
        }

为什么第一个无效,而第二个可以在下面做同样的事情(我正在为此寻找正确的英文表达,但我不记得了.在...下?^^)

Why is the first invalid, whereas the second can do the same underneath (I was searching for the correct english expression for this, but I don't remember it. Under the...? ^^ )

推荐答案

foreach 是一个只读迭代器,它动态迭代实现 IEnumerable 的类,foreach 中的每个循环都会调用 IEnumerable 来获取下一个项目,你拥有的项目是只读引用,您不能重新分配它,但只需调用 item.Value 即可访问它并为读/写属性分配一些值,但仍将 item 的引用作为只读引用.

foreach is a read only iterator that iterates dynamically classes that implement IEnumerable, each cycle in foreach will call the IEnumerable to get the next item, the item you have is a read only reference, you can not re-assign it, but simply calling item.Value is accessing it and assigning some value to a read/write attribute yet still the reference of item a read only reference.

这篇关于为什么我们不能分配 foreach 迭代变量,而我们可以使用访问器完全修改它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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