list.add似乎是在添加对原始对象的引用?

我创建了一些自定义类( NTDropDownNTBaseFreight ),我用它来存储从数据库中检索的数据。 我初始化NTBaseFreight列表和NTBaseFreight 2个列表。

我可以成功使用List.Add将货物添加到List.Add列表中,但是当我调试代码时,我的2个下拉列表只包含1个NTDropDown ,它总是与NTDropDown具有相同的值(我假设这是一个引用问题,但是我做错了什么?

举一个例子,在第二行,如果carrier和carrier_label"001", "MyTruckingCompany"并且我在frt_carriers的if语句上放了一个中断,frt_carriers和frt_modes在它们的列表中只包含1个项目,值"001", "MyTruckingCompany""001", "MyTruckingCompany"的值相同。

码:

 List frt_carriers = new List(); List frt_modes = new List(); List freights = new List(); 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); } 

是的,引用类型列表实际上只是一个引用列表。

您必须为要存储在列表中的每个对象创建一个新实例。

此外, Contains方法比较引用,因此包含相同数据的两个对象不被视为相等。 在列表中的对象属性中查找值。

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

tempDropDown是整个循环中的同一个对象。 如果要添加多个实例,则需要创建它的新实例。

我正在努力弄清楚你正在尝试将tempDropDown添加到列表中的确切方法。