我在C#中有以下代码:
public class ELL
{
public struct RVector
{
private int ndim;
private double[] vector;
public RVector(double[] vector) => (ndim, this.vector) = (vector.Length, vector);
public double this[int i] { get => vector[i]; set => vector[i] = value; }
public override string ToString()
{
string str = "(";
for (int i = 0; i < ndim - 1; i++)
str += vector[i].ToString() + ", ";
str += vector[ndim - 1].ToString() + ")";
return str;
}
}
private static void SwapVectorEntries(RVector b, int m, int n)
{
double temp = b[m];
b[m] = b[n];
b[n] = temp;
}
public static void M(string[] args)
{
var a = new double[4] { 1, 2, 3, 4 };
var b = new RVector(a);
Console.WriteLine(b);
SwapVectorEntries(b, 1, 2); // Why after this command, b will be changed?
Console.WriteLine(b);
}
}
在这个程序中,我创建了一个结构RVector
。之后,我使用具有struct参数的方法SwapVectorEntries
。因为,Struct是value type
,所以我认为方法SwapVectorEntries
不会改变struct参数。但是,在程序中,在命令SwapVectorEntries(b, 1, 2);
之后,b已经改变。请解释一下这个。谢谢!