简体   繁体   English

C#将struct作为参数传递

[英]C# Passing struct as parameter

I have the following code in C#: 我在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 . 在此程序中,我创建了一个RVector结构。 After that, i use a method SwapVectorEntries which have a struct parameter. 之后,我使用具有struct参数的方法SwapVectorEntries Because, Struct is a value type , so i think the method SwapVectorEntries will not change the struct parameter. 因为Struct是一个value type ,所以我认为SwapVectorEntries方法不会更改struct参数。 But, in the program, after the command SwapVectorEntries(b, 1, 2); 但是,在程序中,在命令SwapVectorEntries(b, 1, 2); , b has changed. ,b改变了。 Please explain me about this. 请给我解释一下。 Thank you ! 谢谢 !

Problem is in this.You have an array wich is reference type .When you create your 问题就在这里。您有一个reference type的数组。当您创建自己的

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[]的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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