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

标签 c# list

我创建了几个自定义类(NTDropDownNTBaseFreight),我用它们来存储从数据库检索的数据。我初始化了 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/

相关文章:

c# - foreach 循环非常慢

c# - 在 Windows Phone 中使用 GoBack 方法时如何获取页面的 uri?

python - 从列表中创建一个句子

python - append 到 Python 中的列表 : adds last element every time?

list - 在 Prolog 中将元素附加到列表的开头

javascript - 如何在 Azure Build Pipeline 中打包 JS 应用程序并保存在单独的 C# 存储库中

c# - 根据 bindingcontext 删除 ListView item

c# - 使用 mvvm 导航返回时,何时在 ListView 中重新加载项目

javascript - 如何格式化联合列表中的组标题?

c# - 从文件读取时出现无限循环问题