[英]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.