更新时间:2022-05-09 16:06:10
C#编译器会给你以下错误:
The C# compiler will give you the following error:
不能修改System.Collections.Generic.List.this [INT]'的返回值,因为它不是一个变量
Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable
原因是,结构是值类型,所以当你访问一个列表元素,你实际上将获得已返回列表索引元素的中间副本。
The reason is that structs are value types so when you access a list element you will in fact access an intermediate copy of the element which has been returned by the indexer of the list.
从 MSDN :
错误信息
不能修改的返回值 '前pression',因为它不是一个 变量
Cannot modify the return value of 'expression' because it is not a variable
这是试图修改值 键入是一个结果 中间EX pression。由于 值不坚持,该值将 保持不变。
An attempt was made to modify a value type that was the result of an intermediate expression. Because the value is not persisted, the value will be unchanged.
要解决此错误,存储 的EX pression在结果 中间值,或使用一个参考 键入中间EX pression。
To resolve this error, store the result of the expression in an intermediate value, or use a reference type for the intermediate expression.
解决方案:
 
List<Map> list = new List<Map>() {
new Map(10),
new Map(20),
new Map(30),
new Map(40)
};
Map map = list[2];
map.Size = 42;
list[2] = map;