简体   繁体   中英

C# Passing struct as parameter

I have the following code in 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);
    }
}

In this program, i creates a struct RVector . After that, i use a method SwapVectorEntries which have a struct parameter. Because, Struct is a value type , so i think the method SwapVectorEntries will not change the struct parameter. But, in the program, after the command SwapVectorEntries(b, 1, 2); , b has changed. Please explain me about this. Thank you !

Problem is in this.You have an array wich is reference type .When you create your

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

you have two references to that array.After when you pass your object into the method,

SwapVectorEntries(b, 1, 2);

your object is copied, BUT your new object have the same reference to that array.Here your have only one array and many references to it.

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM