Values of Array are changed even though not passed a reference C#

时间:2015-09-01 21:56:27

标签: c# methods parameter-passing

So in the below code it's a simple script to generate the faces of a cube, I'm curious (and can only find C++ examples here) why the int[] triangles inside of CreateTriangles is able to be assigned to from inside of SetQuad even though I didn't pass it as a reference. I'm very new to C# so forgive me if this is a stupid question but from what I read on MSDN regarding refs there's something I clearly don't understand. I would have thought to get this effect you'd need to use "ref int[] ..."

 private static int SetQuad (int[] triangles, int i, int v00, int v10, int v01, int v11){
            triangles [i] = v00;
            triangles [i + 1] = triangles [i + 4] = v01;
            triangles [i + 2] = triangles [i + 3] = v10;
            triangles [i + 5] = v11;
            return i + 6;
        }

    private void CreateTriangles () {
        int quads = (xSize * ySize + xSize * zSize + ySize * zSize) * 2;
        int[] triangles = new int[quads * 6];
        int ring = (xSize + zSize) * 2;
        int t = 0, v = 0;
        for (int y = 0; y < ySize; y++, v++) {
            for (int q = 0; q < ring - 1; q++, v++) {
                t = SetQuad (triangles, t, v, v + 1, v + ring, v + ring + 1);
            }
            t = SetQuad (triangles, t, v, v - ring + 1, v + ring, v + 1);
        }
        t = CreateTopFace (triangles, t, ring);
        mesh.triangles = triangles;
    }

1 个答案:

答案 0 :(得分:1)

You only need to pass by ref if you want to assign the triangles variable to some other array and have that assignment propagate to the caller.

That's what ref does, it allows assignment to propagate. Because Array<int> is a reference type, you are already passing a reference around (by value) and so modifications to the object's state are automatically "picked up" by the caller, since they are both pointing to the same object.

相关问题