List of Records

前端 未结 3 1271
情书的邮戳
情书的邮戳 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.

提交回复
热议问题