C# List internals

后端 未结 5 1277
渐次进展
渐次进展 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:20

    It's important in .NET programming to have a good understanding of the difference between reference types and value types. This article provides a good overview: http://www.albahari.com/valuevsreftypes.aspx

    In this case, you created two Person objects (Daniel, age 10, and hw, age 44). It's the variables that reference the two objects that created the confusion.


    Person dan = new Person() { Name="daniel", Age=10 };
    

    Here, a local variable, dan, is assigned a reference to the newly created (Daniel, age 10) object.


    people.Add(dan);
    

    Here, the property people[0] is (indirectly via the List.Add method) assigned a reference to the existing (Daniel, age 10) object.


    dan = new Person() { Name = "hw", Age = 44 };
    

    Here, the local variable, dan, is assigned a reference to the newly created (hw, age 44) object. But the property people[0] still holds a reference to the existing (Daniel, age 10) object.

提交回复
热议问题