我在 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
。之后,我使用了一个方法 SwapVectorEntries
,它有一个结构参数。因为,Struct 是一个值类型
,所以我认为方法SwapVectorEntries
不会改变struct 参数。但是,在程序中,在命令 SwapVectorEntries(b, 1, 2);
之后,b 发生了变化。请向我解释一下。谢谢!
最佳答案
问题出在这里。你有一个数组,它是 reference type
.当你创建你的
double[] a = new double[4] { 1, 2, 3, 4 };
RVector b = new RVector(a);
您有两个对该数组的引用。将对象传递给方法后,
SwapVectorEntries(b, 1, 2);
您的对象已被复制,但是您的新对象对该数组有相同的引用。这里您只有一个数组和许多对它的引用。强>
关于C# 传递结构作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33541909/