List passed by ref - help me explain this behaviour

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

    C# just does a shallow copy when it passes by value unless the object in question executes ICloneable (which apparently the List class does not).

    What this means is that it copies the List itself, but the references to the objects inside the list remain the same; that is, the pointers continue to reference the same objects as the original List.

    If you change the values of the things your new List references, you change the original List also (since it is referencing the same objects). However, you then change what myList references entirely, to a new List, and now only the original List is referencing those integers.

    Read the Passing Reference-Type Parameters section from this MSDN article on "Passing Parameters" for more information.

    "How do I Clone a Generic List in C#" from StackOverflow talks about how to make a deep copy of a List.

提交回复
热议问题