C# List internals

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

    Well with that code the List people should not get affected by the 2nd line either.

    Anyway, the List gets a reference if you use .Add() so if you modify that person later, the person in the list is "modified" too (it's the same person), but if you assign the person to someone else you're not affecting the reference, you're assigning the symbol to a new reference.

    e.g.:

    List people = new List(); 
    Person dan = new Person() { Name="daniel", Age=10 }; 
    people.Add(dan);
    
    /* DanData = { Name="daniel", Age=10 }; 
     * `people[0]` maps to "DanData"
     * `dan` maps to "DanData" */
    
    dan.Name = "daniel the first";
    string dansNameInList = people[0].Name; /* equals "daniel the first" */
    
    /* DanData = { Name="daniel the first", Age=10 }; 
     * `people[0]` maps to "DanData"
     * `dan` maps to "DanData" */
    
    people[0].Name = "daniel again";
    string dansName = dan.Name /* equals "daniel again" */
    
    /* DanData = { Name="daniel again", Age=10 }; 
     * `people[0]` maps to "DanData"
     * `dan` maps to "DanData" */
    
    dan = new Person() { Name = "hw", Age = 44 }; 
    string dansNameInListAfterChange = people[0].Name /* equals "daniel again" */
    string dansNameAfterChange = dan.Name /* equals "hw" */
    
    /* DanData = { Name="daniel again", Age=10 }; 
     * NewData = { Name = "hw", Age = 44 }; 
     * `people[0]` maps to "DanData"
     * `dan` maps to "NewData" */
    

提交回复
热议问题