C# 传递结构作为参数

标签 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。之后,我使用了一个方法 SwapVectorEntries ,它有一个结构参数。因为,Struct 是一个值类型,所以我认为方法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);

您的对象已被复制,但是您的新对象对该数组有相同的引用。这里您只有一个数组和许多对它的引用。

enter image description here

关于C# 传递结构作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33541909/

相关文章:

c# - DevExpress LookupEdit 设置 EditValue 不起作用

c# - 尝试将 Gmap.Net 控件添加到工具箱

c++ - struct 中的 cin 和 char 数组指针

c - 从类型 `' 分配给类型 ]'` 时不兼容的类型

c# - 将变量作为设置传递给类一次还是多次传递? C#

function - 如何将函数及其参数传递给另一个函数

c# - 将方法应用于类的成员

c# - "CryptographicException: Cannot find the requested object"证书文件存在

c - 结构内部结构类型的填充

mysql - 如何通过命令行调整mysql参数的大小