【发布时间】:2012-12-05 20:48:58
【问题描述】:
在下面的代码中,结构是从数组和列表中获取的。当按索引获取项目时,数组似乎是通过引用来完成的,而列表似乎是通过值来完成的。有人能解释一下这背后的原因吗?
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;
}
}
将结构定义更改为类可以编译。
【问题讨论】:
-
结构是值类型。列表重载
[]运算符以返回 T 类型的对象。数组的特殊之处在于它们是内置的并且可以直接访问它们的元素:-) -
错误是什么,为什么这么说
array appears to do it by reference whereas the list appears to do it by value? -
@BigM 确切的错误文本是:
Cannot modify the return value of 'System.Collections.Generic.List<ConsoleSandbox2.Program.FloatPoint>.this[int]' because it is not a variable。至于他的报价,实际上或多或少是正确的。列表索引器返回一个副本,而不是数组访问。