调用此函数后输入函数参数更改

tat*_*ngi -1 c#

我正在使用C#我有一个功能:

public double[] PerformBeeDance(double[] vector, double r) {
            int index = rand.Next(0, vector.Length);
            double[] result = vector;
            result[index] = vector[index] + rand.NextDouble() * r;
            return result;
        }
Run Code Online (Sandbox Code Playgroud)

我把bees[i].Position它放到这个函数中并在调用之后:

newbee.Position = PerformBeeDance(bees[i].Position, r); 
Run Code Online (Sandbox Code Playgroud)

bees[i].Position正在改变newbee.Position但它应该保持不变.

这段代码出了什么问题?

dov*_*vid 5

double[] 是一个ReferenceType,因此虽然它作为副本传递,但副本只是引用,它们都引用同一个实例.

编辑

可能的解决方案正如@RaymondChen在评论中指出的那样,是Array.Clone:

public double[] PerformBeeDance(double[] vector, double r)
{
    int index = rand.Next(0, vector.Length);
    double[] result = vector.Clone();
    result[index] = vector[index] + rand.NextDouble() * r;
    return result;
}
Run Code Online (Sandbox Code Playgroud)

或使用来电代码制作副本:

newbee.Position = PerformBeeDance(bees[i].Position.Clone(), r); 
Run Code Online (Sandbox Code Playgroud)

  • 使用`Array.Clone`制作新副本. (2认同)