list.add seems to be adding a reference to the original object?

后端 未结 2 597
遥遥无期
遥遥无期 2020-12-10 16:01

I have created a couple custom classes (NTDropDown and NTBaseFreight) which I use to store data that I retrieve from a DB. I initialize a List of <

相关标签:
2条回答
  • 2020-12-10 16:46

    Yes, a list of reference types is actually just a list of references.

    You have to create a new instance for each object that you want to store in the list.

    Also, the Contains method compares references, so two objects containing the same data are not considered to be equal. Look for a value in the properties of the objects in the list.

    if (!frt_carriers.Any(c => c.label == tempFreight.carrier_label)) {
      NTDropDown tempDropDown = new NTDropDown {
        value = tempFreight.carrier,
        label = tempFreight.carrier_label
      };
      frt_carriers.Add(tempDropDown);
    }
    
    0 讨论(0)
  • 2020-12-10 16:58

    tempDropDown is the same object throughout the whole loop. You will need to create a new instance of it if you want to add more than one.

    I'm having a hard time trying to figure out what exactly your'e trying to do with adding that tempDropDown the the list.

    0 讨论(0)
提交回复
热议问题