【发布时间】:2019-11-29 11:16:34
【问题描述】:
请考虑以下代码:
public class Program {
public struct A
{
public int Prop {get;set;}
}
public static void Main()
{
var obj = new A();
obj.Prop = 10;
var list = new List<A>(){obj};
foreach(var l in list) {
l.Prop = 20; //here I'm getting compile time error "Cannot modify members of 'l' because it is a 'foreach iteration variable'"
}
}
}
所以我的问题是:为什么在迭代结构列表时不能分配结构属性? 请注意,即使像这样使用简单的 for 进行迭代:
for (int i=0; i<list.Count(); ++i)
list[i].Prop = 20;
我仍然收到编译时错误...
【问题讨论】:
-
关于 for 循环。您需要创建一个结构的副本。见:Changing the value of an element in a list of structs
标签: c# list loops compiler-errors value-type