Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 带结构的数组和列表离散_C#_List_Struct - Fatal编程技术网

C# 带结构的数组和列表离散

C# 带结构的数组和列表离散,c#,list,struct,C#,List,Struct,在下面的代码中,从数组和列表中获取结构。按索引获取项时,数组似乎按引用执行,而列表似乎按值执行。有人能解释一下这背后的原因吗 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 { pu

在下面的代码中,从数组和列表中获取结构。按索引获取项时,数组似乎按引用执行,而列表似乎按值执行。有人能解释一下这背后的原因吗

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;
    }
}
struct浮点{
公共浮点数(浮点数x、浮点数y、浮点数z){
这个.x=x;
这个。y=y;
这个。z=z;
}
公共浮动x,y,z;
}
课堂测试{
公共静态int Main(字符串[]args){
浮点[]点s1={新浮点(1,2,3)};
var points2=new System.Collections.Generic.List();
点2.添加(新浮点(1,2,3));
点1[0].x=0;//不是错误
点2[0].x=0;//编译错误
返回0;
}
}

将结构定义更改为类会使两者都编译。

当您获得结构时,它总是按值。该结构将被复制,您无法获得对它的引用

不同之处在于,您可以直接在数组中访问scstruct,但不能在列表中访问。在数组中更改结构中的属性时,可以直接访问该属性,但要对列表执行相同操作,必须获取结构,设置属性,然后将结构存储回列表中:

FloatPoint f = points2[0];
f.x = 0;
points2[0] = f;
早期版本的编译器允许您编写现有的代码,但对于列表,它将生成类似以下内容的代码:

FloatPoint f = points2[0];
f.x = 0;

也就是说,它将读取结构,更改它,然后默默地将更改后的结构扔掉。编译器已更改,在这种情况下出现错误。

结构是值类型。列出重载
[]
运算符以返回类型为T的对象。数组的特殊之处在于它们是内置的,可以直接访问其元素:-)错误是什么,为什么说这个
数组似乎是通过引用实现的,而列表似乎是通过值实现的呢?@BigM确切的错误文本是:
无法修改“System.Collections.Generic.list.this[int]”的返回值,因为它不是一个变量。至于他的话,实际上或多或少是正确的。列表索引器返回一个副本,而数组访问不返回。因此,强烈建议您使结构不可变。您可以使用
readonly
public readonly float x,y,z。现在,每次要进行更改时,都必须将整个struct对象替换为一个新对象。数组和列表也是如此:
point[0]=newfloatpoint(0,point[0].y,point[0].z)