为什么在没有 ref 的情况下将 list 传递给函数,就像通过 ref 传递一样? [英] Why is list when passed without ref to a function acting like passed with ref?

查看:47
本文介绍了为什么在没有 ref 的情况下将 list 传递给函数,就像通过 ref 传递一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我没有犯大错,这种行为对我来说很奇怪.我将在下面发布示例代码,而不是解释,请告诉我为什么我得到输出 x 而不是 y.

If I did not get this terribly wrong, this behaviour is strange for me. Rather than explaining, I'll post a sample code below and please tell me why does I get output x and not y.

    private void button1_Click(object sender, EventArgs e)
    {
        List<int> l = new List<int>() { 1, 2, 3 };
        Fuss(l);
        MessageBox.Show(l.Count.ToString());
    }

    private void Fuss(List<int> l)
    {
        l.Add(4);
        l.Add(5);
    }

输出应该是 3.但我得到的输出是 5.我知道如果我这样做,输出可以是 5:

Output should, I assume would be 3. But I get the output as 5. I understand the output can be 5 if I do this:

    private void button1_Click(object sender, EventArgs e)
    {
        List<int> l = new List<int>() { 1, 2, 3 };
        Fuss(ref l);
        MessageBox.Show(l.Count.ToString());
    }

    private void Fuss(ref List<int> l)
    {
        l.Add(4);
        l.Add(5);
    }

推荐答案

它不像它通过 ref 传递的那样.

It does not act like its passed by ref.

void ChangeMe(List<int> list) {
  list = new List<int>();
  list.Add(10);
}
void ChangeMeReally(ref List<int> list) {
  list = new List<int>();
  list.Add(10);
}

试试吧.你注意到区别了吗?

Try it. Do you notice the difference?

如果在没有 ref 的情况下传递它,则只能更改列表(或任何引用类型)的内容(因为正如其他人所说,您正在传递对堆上对象的引用,从而更改相同的内存").

You can only change the contents of list (or any reference type) if you pass it without a ref (because as others have said, you are passing a reference to the object on the heap and thus change the same "memory").

但是你不能改变list",list"是一个指向List类型对象的变量.如果通过引用传递列表"(使其指向其他地方),则只能更改列表".您将获得引用的副本,如果更改,则只能在您的方法中观察到.

However you cannot change "list", "list" is a variable that points to an object of type List. You can only change "list" if you pass it by reference (to make it point somewhere else). You get a copy of the reference, which if changed, can only be observed inside your method.

这篇关于为什么在没有 ref 的情况下将 list 传递给函数,就像通过 ref 传递一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆