为什么我可以在不指定"ref"的情况下从方法更改Struct的int []属性?

AMi*_*ico 1 c# struct pass-by-reference

从一个方法,我可以传递一个包含整数数组的结构,并更改数组中的值.我不确定我完全理解为什么我能做到这一点.有人可以解释为什么我可以更改存储在int []中的值吗?

    private void DoIt(){

        SearchInfo a = new SearchInfo();
        a.Index = 1;
        a.Map = new int[] { 1 };

        SearchInfo b = new SearchInfo();
        b.Index = 1;
        b.Map = new int[] { 1 };

        ModifyA(a);
        ModifyB(ref b);

        Debug.Assert(a.Index == 1);
        Debug.Assert(a.Map[0] == 1, "why did this change?");

        Debug.Assert(b.Index == 99);
        Debug.Assert(b.Map[0] == 99);

    }
    void ModifyA(SearchInfo a) {
        a.Index = 99;
        a.Map[0] = 99;
    }
    void ModifyB(ref SearchInfo b) {
        b.Index = 99;
        b.Map[0] = 99;
    }
    struct SearchInfo {
        public int[] Map;
        public int Index;
    }
Run Code Online (Sandbox Code Playgroud)

LBu*_*kin 5

在C#中,引用按值传递.传递给方法或存储在另一个类的实例中时,不会复制数组. - 传递对数组的引用.这意味着接收对数组的引用(直接或作为另一个对象的一部分)的方法可以修改该数组的元素.

与C++之类的语言不同,您不能在C#中声明"不可变"数组 - 但是您可以使用类似List的类,它们具有可用的只读包装器以防止对集合进行修改.