List passed by ref - help me explain this behaviour

后端 未结 8 2287
名媛妹妹
名媛妹妹 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

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

提交回复
热议问题