由参传递的列表 - 帮我解释这种现象 [英] List passed by ref - help me explain this behaviour

查看:142
本文介绍了由参传递的列表 - 帮我解释这种现象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看下面的程序:

 类测试
{
    清单< INT> myList中=新名单< INT>();    公共无效TestMethod的()
    {        myList.Add(100);
        myList.Add(50);
        myList.Add(10);        变更(myList中);        的foreach(INT我在myList中)
        {
            Console.WriteLine(ⅰ);
        }
    }    私人无效变更(列表< INT> myList中)
    {
        myList.Sort();        清单< INT> myList2 =新的List< INT>();
        myList2.Add(3);
        myList2.Add(4);        myList中= myList2;
    }
}

我以为 myList中将被裁判已经过去了,输出会

  3
4

该列表确实是由裁判通过,但只有排序功能生效。下面的语句 myList中= myList2; 没有效果。

所以输出实际上是:

  10
50
100

你能帮我解释这种现象?如果确实 myList中不是的通过按REF 的(因为它似乎从 myList中= myList2 未生效),请问 myList.Sort()生效?

我是假设甚至语句不生效,并且输出是:

  100
50
10


解决方案

正在传递的参考列表的,但您的不是传递列表可变引用的 - 所以,当你调用变更中的变量的值的(即基准 - 认为指针)是复制 - 和更改的参数值内变更 的的的由可见TestMethod的

尝试:

 私人无效变更(参考表< INT> myList中){...}
...
变更(REF myList中);

这然后通过的为引用的本地变量 myRef (如 TestMethod的);现在,如果你重新分配变更你也重新分配变量的里面的参数中 TestMethod的

Take a look at the following program:

class Test
{
    List<int> myList = new List<int>();

    public void TestMethod()
    {

        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList(myList);

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList(List<int> myList)
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}

I assumed myList would have passed by ref, and the output would

3
4

The list is indeed "passed by ref", but only the sort function takes effect. The following statement myList = myList2; has no effect.

So the output is in fact:

10
50
100

Can you help me explain this behavior? If indeed myList is not passed-by-ref (as it appears from myList = myList2 not taking effect), how does myList.Sort() take effect?

I was assuming even that statement to not take effect and the output to be:

100
50
10

解决方案

You are passing a reference to the list, but your aren't passing the list variable by reference - so when you call ChangeList the value of the variable (i.e. the reference - think "pointer") is copied - and changes to the value of the parameter inside ChangeList aren't seen by TestMethod.

try:

private void ChangeList(ref List<int> myList) {...}
...
ChangeList(ref myList);

This then passes a reference to the local-variable myRef (as declared in TestMethod); now, if you reassign the parameter inside ChangeList you are also reassigning the variable inside TestMethod.

这篇关于由参传递的列表 - 帮我解释这种现象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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