List passed by ref - help me explain this behaviour

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

    Initially, it can be represented graphically as follow:

    Init states

    Then, the sort is applied myList.Sort(); Sort collection

    Finally, when you did: myList' = myList2, you lost the one of the reference but not the original and the collection stayed sorted.

    Lost reference

    If you use by reference (ref) then myList' and myList will become the same (only one reference).

    Note: I use myList' to represent the parameter that you use in ChangeList (because you gave the same name as the original)

提交回复
热议问题