簡體   English   中英

C#將struct作為參數傳遞

[英]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改變了。 請給我解釋一下。 謝謝 !

問題就在這里。您有一個reference type的數組。當您創建自己的

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

您對該數組有兩個引用。將對象傳遞給方法后,

SwapVectorEntries(b, 1, 2);

復制對象, 新對象對該數組具有相同的引用 。這里只有一個數組,並且對該數組有很多引用。

在此處輸入圖片說明

B本身不作為引用傳遞,但是b的副本具有對相同double[]的引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM