C# List internals

后端 未结 5 1238
渐次进展
渐次进展 2021-01-07 05:47

What exactly happens when adding an object to a collection such as List?

List people = new List();
Person dan = new Person() { Na         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-07 06:30

    Well, the code you've shown doesn't actually add anything to the list at all. I assume you meant to have:

    people.Add(dan);
    

    in there somewhere?

    But yes, the List contains references to objects. It doesn't know about where the references have come from. It's worth being clear about the difference between a variable and its value. When you call:

    people.Add(dan);
    

    that copies the value of the argument expression (dan) in this case as the initial value of the parameter within List.Add. That value is just a reference - it has no association with the dan variable, other than it happened to be the value of the variable at the time when List.Add was called.

    It's exactly the same as the following situation:

    Person p1 = new Person { Name = "Jon" };
    p2 = p1;
    p1 = new Person { Name = "Dan" };
    

    Here, the value of p2 will still be a reference to the person with the name "Jon" - the second line just copies the value of p1 to p2 rather than associating the two variables together. Once you understand this, you can apply the same logic to method arguments.

提交回复
热议问题