一、问题的起源 如下的代码是错误的,无法编译通过 struct Point { public int X; public int Y; } List<Point> points = new List<Point> { new Point { X = 1, Y = 2 } }; points[0].X = 10; // 编译错误!无法修改副本的字段
二、原因分析
在C#中,结构体(struct
)是值类型,当其存储在List<T>
中时,直接通过索引访问获取的是该结构体的副本,而非原始实例的引用。因此,直接修改结构体字段的值会导致编译错误,因为你在尝试修改一个临时副本,这个没有意义。
上述代码的正确做法:
// 取出副本 Point temp = points[0]; // 修改副本 temp.X = 10; // 将副本重新赋值回列表 points[0] = temp;
三、如果是类,下属代码就没有问题,因为list中存储的是对象的指针。可以直接修改其中的变量。
class Point { public int X { get; set; } public int Y { get; set; } }
List<Point> points = new List<Point> { new Point { X = 1, Y = 2 } };
points[0].X = 10;