在以下代码中,从数组和列表中获取结构.通过索引获取项目时,数组似乎通过引用执行,而列表似乎按值执行.有人可以解释这背后的原因吗?
struct FloatPoint {
public FloatPoint (float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public float x, y, z;
}
class Test {
public static int Main (string[] args) {
FloatPoint[] points1 = { new FloatPoint(1, 2, 3) };
var points2 = new System.Collections.Generic.List<FloatPoint>();
points2.Add(new FloatPoint(1, 2, 3));
points1[0].x = 0; // not an error
points2[0].x = 0; // compile error
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
将结构定义更改为类可以进行编译.
当你得到一个结构时,它总是按值.结构将被复制,您不会获得它的引用.
不同之处在于您可以直接在数组中访问sctruct,但不能在列表中访问.当您更改数组中结构中的属性时,您可以直接访问该属性,但是为了对要获取结构的列表执行相同操作,请设置属性,然后将结构存储回列表中:
FloatPoint f = points2[0];
f.x = 0;
points2[0] = f;
Run Code Online (Sandbox Code Playgroud)
早期版本的编译器可以让你编写你拥有的代码,但是对于一个列表,它会生成类似于这样的代码:
FloatPoint f = points2[0];
f.x = 0;
Run Code Online (Sandbox Code Playgroud)
即它会读取结构,更改它,并默默地抛出已更改的结构.在这种情况下,编译器已更改为出错.