List passed by ref - help me explain this behaviour

后端 未结 8 2308
名媛妹妹
名媛妹妹 2020-12-02 05:39

Take a look at the following program:

class Test
{
    List myList = new List();

    public void TestMethod()
    {
        myList.Add         


        
8条回答
  •  清歌不尽
    2020-12-02 06:06

    While I agree with what everyone has said above. I have a different take on this code. Basically you're assigning the new list to the local variable myList not the global. if you change the signature of ChangeList(List myList) to private void ChangeList() you'll see the output of 3, 4.

    Here's my reasoning... Even though list is passed by reference, think of it as passing a pointer variable by value When you call ChangeList(myList) you're passing the pointer to (Global)myList. Now this is stored in the (local)myList variable. So now your (local)myList and (global)myList are pointing to the same list. Now you do a sort => it works because (local)myList is referencing the original (global)myList Next you create a new list and assign the pointer to that your (local)myList. But as soon as the function exits the (local)myList variable is destroyed. HTH

    class Test
    {
        List myList = new List();
        public void TestMethod()
        {
    
            myList.Add(100);
            myList.Add(50);
            myList.Add(10);
    
            ChangeList();
    
            foreach (int i in myList)
            {
                Console.WriteLine(i);
            }
        }
    
        private void ChangeList()
        {
            myList.Sort();
    
            List myList2 = new List();
            myList2.Add(3);
            myList2.Add(4);
    
            myList = myList2;
        }
    }
    

提交回复
热议问题