我创建了几个自定义类(NTDropDown
和 NTBaseFreight
),我用它们来存储从数据库检索的数据。我初始化了 NTBaseFreight
列表和 NTDropDown
的 2 个列表。
我可以成功地使用 List.Add
将 cargo 添加到 cargo 列表中,但是当我调试代码时,我的 2 个下拉列表只包含 1 个 NTDropDown
,它总是与 NTDropDown
具有相同的值(我假设这是一个引用问题,但我做错了什么)?
举个例子,在第二行,如果承运人和 carrier_label
是 "001", "MyTruckingCompany"
并且我在 if 语句上打断了frt_carriers
,frt_carriers 和 frt_modes 在它们的列表中只包含一项,值 "001", "MyTruckingCompany"
...NTDropDown 中的值相同
。
代码:
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);
}
最佳答案
是的,引用类型列表实际上只是引用列表。
您必须为要存储在列表中的每个对象创建一个新实例。
此外,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);
}
关于c# - list.add 似乎在添加对原始对象的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13275768/