C# 交错数组会自行更改

本文关键字:数组 | 更新日期: 2023-09-27 17:56:44

我遇到了一个问题。我创建了一个交错数组(输入),然后我浏览了一些函数,并期望从中创建另一个交错数组(输出)。但不知何故,原始阵列也在此过程中发生了变化。如何避免原始数组中的更改?

double[][] input;
    double[][] output;
    private void button1_Click(object sender, EventArgs e)
    {
        input = new double[][]
        {
            new double[] {0,1,2,3 },
            new double[] {9,8 },
            new double[] {14,5,0 },
            new double[] {2.0,2.3,2.5 }
        };
        output = function(input);
    }
    static double[][] function (double[][] ins)
    {
        double[][] ous = ins;
        int leng = ins.GetLength(0);
        for (int i = 0; i < leng; i++)
        {
            int lung = ins[i].GetLength(0);
            for (int j = 0; j < lung; j++)
                ous[i][j] += 14.4;
        }
        return ous;
    }

C# 交错数组会自行更改

问题是ous变量指向与ins(引用)相同的数组。您应该将其复制到新阵列。例如使用 linq:

static T[][] CopyArray<T>(T[][] source)
{
    return source.Select(s => s.ToArray()).ToArray();
}

并使用它:

double[][] ous = CopyArray(ins);