[英]C# Passing struct as parameter
我在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改变了。 请给我解释一下。 谢谢 !
B本身不作为引用传递,但是b的副本具有对相同double[]
的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.