List of Records

前端 未结 3 1270
情书的邮戳
情书的邮戳 2021-01-29 07:06

The following code seems to add a new record to the list but overwrites all the record with the last record created. I can get it to work fine with ...

lpr.Add(n         


        
相关标签:
3条回答
  • 2021-01-29 07:15

    pr is a reference to an object. When you change the values of pr you are changing the values of the same object and adding that reference to the list. So your list consists of several references to the same object, and the last values you set will be reflected by each reference.

    You can solve it by adding

    pr = new personRecord();
    

    before each block to ensure that pr is referenceing a new object each time.

    When you do

    lpr.Add(new personRecord(){Age = pr.Age,Name = pr.Name});
    

    You are adding a reference to a new object and just copying the values from the single pr reference.

    0 讨论(0)
  • 2021-01-29 07:15

    Possible duplicate of what is different between Passing by value and Passing by reference using C#.

    But as pr is a class this means that when you are adding it to the list you are actually only storing the reference to that variable. When you change that variable the next 3 times what you are actually changing is the values located at the memory of the original reference. So your list actually contains 4 references to the same object with the same values.

    If you are attempting to reuse the same object (as this may be a model for your view) you should make a new object with it's values and add this new object to your list.

    0 讨论(0)
  • 2021-01-29 07:33

    Is this what you are trying to achieve?

    private void button1_Click(object sender, EventArgs e)
    {
      List<personRecord> lpr = new List<personRecord>
      {
        new personRecord { Age = 40, Name = "Bob" },
        new personRecord { Age = 30, Name = "Steve"},
        new personRecord { Age = 44, Name = "Phil"},
        new personRecord { Age = 33, Name = "Sue"},
     };
    }
    
    0 讨论(0)
提交回复
热议问题