C#将struct作为参数传递

时间:2015-11-05 10:16:05

标签: c# struct parameters

我在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已经改变。请解释一下这个。谢谢!

2 个答案:

答案 0 :(得分:4)

问题在于此。你有一个reference type的数组。当你创建

double[] a = new double[4] { 1, 2, 3, 4 };
RVector b = new RVector(a);

你有两个对该数组的引用。当你将对象传递给方法时,

SwapVectorEntries(b, 1, 2);

您的对象已被复制,但是您的新对象与该数组具有相同的引用。您只有一个数组且多次引用它。< /强>

enter image description here

答案 1 :(得分:2)

B本身不作为参考传递,但b的副本具有对同一double[]的引用。