Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

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

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 NTBaseFreight and 2 lists for NTDropDown.

I can successfully use List.Add to add freights to the freights list, but as I debug the code, my 2 dropdown lists contain only 1 NTDropDown, which always has the same values as NTDropDown (I'm assuming this is a referencing problem, but what am I doing wrong)?

To give an example, on the second row, if the carrier and carrier_label were "001", "MyTruckingCompany" and I put a break on the if statement for frt_carriers, both frt_carriers and frt_modes would contain only 1 item in their list, with the values "001", "MyTruckingCompany"...the same values in NTDropDown.

Code:

List<NTDropDown> frt_carriers = new List<NTDropDown>();
List<NTDropDown> frt_modes = new List<NTDropDown>();
List<NTBaseFreight> freights = new List<NTBaseFreight>();
NTDropDown tempDropDown = new NTDropDown();
NTBaseFreight tempFreight = new NTBaseFreight();

//....Code to grab data from the DB...removed

while (myReader.Read())
{
    tempFreight = readBaseFreight((IDataRecord)myReader);

    //check if the carrier and mode are in the dropdown list (add them if not)
    tempDropDown.value = tempFreight.carrier;
    tempDropDown.label = tempFreight.carrier_label;
    if (!frt_carriers.Contains(tempDropDown)) frt_carriers.Add(tempDropDown);

    tempDropDown.value = tempFreight.mode;
    tempDropDown.label = tempFreight.mode_label;
    if (!frt_modes.Contains(tempDropDown)) frt_modes.Add(tempDropDown);

    //Add the freight to the list
    freights.Add(tempFreight);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...