我知道值类型应该是不可变的,但这只是一个建议,而不是一个规则,对吧?那么为什么我不能做这样的事情:
struct MyStruct
{
public string Name { get; set; }
}
public class Program
{
static void Main(string[] args)
{
MyStruct[] array = new MyStruct[] { new MyStruct { Name = "1" }, new MyStruct { Name = "2" } };
foreach (var item in array)
{
item.Name = "3";
}
//for (int i = 0; i < array.Length; i++)
//{
// array[i].Name = "3";
//}
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
代码中的foreach循环不会编译,而注释for循环工作正常.错误消息:
无法修改'item'的成员,因为它是'foreach迭代变量'
这是为什么?
据我了解,C#的foreach迭代变量是不可变的.
这意味着我不能像这样修改迭代器:
foreach (Position Location in Map)
{
//We want to fudge the position to hide the exact coordinates
Location = Location + Random(); //Compiler Error
Plot(Location);
}
Run Code Online (Sandbox Code Playgroud)
我无法直接修改迭代器变量,而是必须使用for循环
for (int i = 0; i < Map.Count; i++)
{
Position Location = Map[i];
Location = Location + Random();
Plot(Location);
i = Location;
}
Run Code Online (Sandbox Code Playgroud)
来自C++背景,我认为foreach是for循环的替代品.但是由于上述限制,我通常会回退使用for循环.
我很好奇,使迭代器不可变的原理是什么?
编辑:
这个问题更多的是一个好奇的问题,而不是一个编码问题.我很欣赏编码答案,但我不能将它们标记为答案.
此外,上面的例子过于简化了.这是我想要做的C++示例:
// The game's rules:
// - The "Laser Of Death (tm)" moves around the game board from the
// start area (index …Run Code Online (Sandbox Code Playgroud) 我发现了这句话:
"在对象列表中使用foreach时,迭代对象实例不可编辑,但对象属性是可编辑的"
有人可以用一个简单的例子来演示上面的内容吗?
让我重新说一句(因为我发现两个版本的声明),也许这句话更清楚:
"在元素列表中使用foreach时,提供元素的迭代变量是只读的,但元素属性是可编辑的 "
我正在尝试搜索字典以查看它是否具有某个值,如果是,则更改它.这是我的代码:
foreach (var d in dictionary)
{
if (d.Value == "red")
{
d.Value = "blue";
}
}
Run Code Online (Sandbox Code Playgroud)
在visual studio中,当我逐步调试代码时,我可以看到它改变了值,然后当它到达foreach循环再次重复它会抛出异常
"集合已被修改;枚举操作可能无法执行"
我该如何解决?
c# ×4
asp.net ×1
dictionary ×1
exception ×1
foreach ×1
generic-list ×1
immutability ×1
value-type ×1