为什么当没有裁判传递到演戏像裁判通过了一项功能列表? [英] Why is list when passed without ref to a function acting like passed with ref?

查看:115
本文介绍了为什么当没有裁判传递到演戏像裁判通过了一项功能列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我没有得到这个可怕的错误,这种行为很奇怪我。而不是解释,我会后下方的示例代码和请告诉我为什么我得到的输出x,而不是年。



 私人无效的button1_Click(对象发件人,EventArgs五)
{
名单,LT; INT> L =新列表与所述; INT>(){1,2,3};
弗斯(L);
MessageBox.Show(l.Count.ToString());
}

私人无效弗斯(列表< INT→1)
{
l.Add(4);
l.Add(5);
}



输出应,我以为会是3。但我得到的输出5我明白输出可以是5,如果我这样做:

 私人无效的button1_Click(对象发件人,EventArgs五)
{
名单,LT; INT> L =新列表与所述; INT>(){1,2,3};
弗斯(REF L);
MessageBox.Show(l.Count.ToString());
}

私人无效弗斯(参考表< INT→1)
{
l.Add(4);
l.Add(5);
}


解决方案

它并不像它的由裁判通过

 无效ChangeMe(列表< INT>名单){
名单=新名单,LT; INT>( );
list.Add(10);
}
无效ChangeMeReally(参考表< INT>名单){
名单=新名单,LT; INT>();
list.Add(10);
}



试试吧。你注意到有什么区别?



您只能更改列表的内容(或任何引用类型),如果你传递没有REF(因为正如其他人所说,你传递给一个参考在堆对象,从而改变了相同的内存)。



但是你不能改变清单,清单是指向类型的对象变量列表。您只能更改排行榜,如果你按引用传递它(将它指向其他地方)。你得到的参考,这要是改变了,只能你的方法内部观察的一个副本。


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);
    }

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);
    }

解决方案

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?

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").

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.

这篇关于为什么当没有裁判传递到演戏像裁判通过了一项功能列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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