C# 传递结构作为参数
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
。之后,我使用具有结构参数的方法 SwapVectorEntries
。因为,Struct是一个value type
,所以我认为方法SwapVectorEntries
不会改变struct参数。但是,在程序中,在命令SwapVectorEntries(b, 1, 2);
之后,b发生了变化。请向我解释一下。谢谢!
B 本身未作为引用传递,但 b 的副本具有对相同 double[]
.
的引用
问题出在 this.You 有一个数组 reference type
。当您创建
double[] a = new double[4] { 1, 2, 3, 4 };
RVector b = new RVector(a);
当您将对象传递给方法时,您有两个对 array.After 的引用,
SwapVectorEntries(b, 1, 2);
您的对象已被复制,但是您的新对象具有 相同的引用 array.Here 您只有一个数组以及 对其的多次引用。
我在 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是一个value type
,所以我认为方法SwapVectorEntries
不会改变struct参数。但是,在程序中,在命令SwapVectorEntries(b, 1, 2);
之后,b发生了变化。请向我解释一下。谢谢!
B 本身未作为引用传递,但 b 的副本具有对相同 double[]
.
问题出在 this.You 有一个数组 reference type
。当您创建
double[] a = new double[4] { 1, 2, 3, 4 };
RVector b = new RVector(a);
当您将对象传递给方法时,您有两个对 array.After 的引用,
SwapVectorEntries(b, 1, 2);
您的对象已被复制,但是您的新对象具有 相同的引用 array.Here 您只有一个数组以及 对其的多次引用。