gpt4 book ai didi

c# - 通过列表和数组中的索引获取结构项

转载 作者:太空狗 更新时间:2023-10-29 20:27:08 25 4
gpt4 key购买 nike

当我使用 struct 数组(例如 System.Drawing.Point)时,我可以通过索引获取项目并更改它。

例如(这段代码工作正常):

Point[] points = new Point[] { new Point(0,0), new Point(1,1), new Point(2,2) };
for (int i = 0; i < points.Length; i++)
{
points[i].X += 1;
}

但是当我使用 List 时它不起作用:

Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable

示例(此代码无法正常工作):

List<Point> points = new List<Point>  { new Point(0,0), new Point(1,1), new Point(2,2) };
for (int i = 0; i < points.Count; i++)
{
points[i].X += 1;
}

我知道,当我按索引获取列表项时,我得到了它的副本并且编译器提示我没有犯错误,但为什么采用数组索引的元素工作方式不同?

最佳答案

这是因为对于数组 points[i]显示对象所在的位置。换句话说,基本上是 points[i]因为数组是内存中的一个指针。因此,您在内存中记录执行操作,而不是在某些副本上。

List<T> 不是这种情况:它在内部使用数组,但通过方法进行通信,导致这些方法会将值复制出内部数组,显然修改这些副本没有多大意义:你会立即忘记它们,因为你没有编写复制回内部数组。

按照编译器的建议,解决这个问题的方法是:

(3,11): error CS1612: Cannot modify a value type return value of `System.Collections.Generic.List<Point>.this[int]'. Consider storing the value in a temporary variable

因此您可以使用以下“技巧”:

List<Point> points = new List<Point>  { new Point(0,0), new Point(1,1), new Point(2,2) };
for (int i = 0; i < points.Count; i++) {
Point p = points[i];
p.X += 1;
points[i] = p;
}

因此您将副本读入临时变量,修改副本,然后将其写回 List<T> .

关于c# - 通过列表和数组中的索引获取结构项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34091314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com