通过列表和数组中的索引获取结构项 [英] Get struct item by index in list and array

查看:108
本文介绍了通过列表和数组中的索引获取结构项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用struct s的数组(例如System.Drawing.Point)时,我可以按索引获取项目并进行更改.

When I use an array of structs (for example System.Drawing.Point), I can get item by index and change it.

例如(此代码可以正常工作):

For example (This code work fine):

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;
}

但是当我使用列表时,它不起作用:

but when i use List it's not work:

无法修改的返回值 'System.Collections.Generic.List.this [int]' 因为它不是变量

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

示例(此代码无法正常运行):

Example(This code didn't work fine):

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;
}

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

I know that when I get list item by index I got copy of it and compiler hints that I did not commit an error, but why take the elements of the array index works differently?

推荐答案

这是因为对于数组points[i]显示对象所在的位置.换句话说,数组的points[i]基本上是内存中的 pointer .因此,您可以在内存中而不是在某些副本上执行记录中的记录 .

This is because for the array points[i] shows where the object is located. In other words, basically points[i] for an array is a pointer in memory. You thus perform operations on-the-record in memory, not on some copy.

List<T>并非如此:它在内部使用数组,但是通过方法进行通信,导致这些方法将从内部数组中复制值,并且显然修改这些副本没有多大意义. :由于您没有将副本写回到内部阵列,因此您会立即忘记它们.

This is not the case for List<T>: it uses an array internally, but communicates through methods resulting in the fact that these methods will copy the values out of the internal array, and evidently modifying these copies does not make much sense: you immediately forget about them since you do not write the copy back to the internal array.

解决此问题的一种方法是,如编译器建议的那样:

A way to solve this problem is, as the compiler suggests:

(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

因此您可以使用以下"技巧":

So you could use the following "trick":

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>.

So you read the copy into a temporary variable, modify the copy, and write it back to the List<T>.

这篇关于通过列表和数组中的索引获取结构项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆