从列表中设置System.Windows.Point的Y坐标会产生修改错误

当我从列表中访问Point时,我在设置Point的Y坐标时遇到了一些麻烦。

例如,这有效。

System.Windows.Point test = new System.Windows.Point(6,5); test.Y = 6; 

但是,如果我有一个点列表,我通过列表访问一个点来设置Y坐标,我收到一个错误。

 List bfunction = new List(); bfunction.Add(new System.Windows.Point(0, 1)); bfunction[0].Y = 6; 

bfunction [0]带有下划线并给出错误“无法修改’System.Collections.Generic.List.this [int]’的返回值,因为它不是变量。”

任何帮助,将不胜感激。

基本上,编译器阻止你犯错误。 当您访问将返回该点副本bfunction[0]时。 不幸的是, Point (IMO)是一个可变结构。 因此,如果编译器允许您更改副本,那么该副本将被丢弃,并且该语句将毫无意义。 相反,您需要使用变量来获取副本,在那里进行更改,然后将其放回列表中:

 Point point = bfunction[0]; point.Y = 6; bfunction[0] = point; 

如果Point是引用类型,则不需要这样做,如果Point不可变值类型,则您没有机会发出错误。 你仍然需要单独获取和设置,但它可能是这样的:

 bfunction[0] = bfunction[0].WithY(6); 

…其中WithY将返回一个Point值,该值与原始值具有相同的X值,但指定的Y

我有同样的问题,谢谢你的回复。

这是我的解决方案:

 if (reset == false && run == true) { for ( int i = 0;i < locations.Count;i++) { double stepX = rnd.Next(-1, 2) * 5 * rnd.NextDouble(); double stepY = rnd.Next(-1, 2) * 5 * rnd.NextDouble(); double stepZ = rnd.Next(-1, 2) * 5 * rnd.NextDouble(); Vector3d transform = new Vector3d(stepX, stepY, stepZ); locations[i] += transform; // Constrain points to boundary conditions Point3d ptx = locations[i]; // make temp variable to hold all points ptx.X = CV.Constrain(ptx.X, 0, bX - 1); // access X coordinates and modify them locations[i] = ptx; // assign new X coordinates to points in List Point3d pty = locations[i]; pty.Y = CV.Constrain(pty.Y, 0, bY - 1); locations[i] = pty; Point3d ptz = locations[i]; ptz.Z = CV.Constrain(ptz.Z, 0, bZ - 1); locations[i] = ptz; Component.ExpireSolution(true); } }