【问题标题】:list.add seems to be adding a reference to the original object?list.add 似乎是在添加对原始对象的引用?
【发布时间】:2012-11-07 18:22:16
【问题描述】:

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

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

举个例子,在第二行,如果运营商和carrier_label"001", "MyTruckingCompany",并且我在frt_carriers 的 if 语句上打了个断点,那么 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);
}

【问题讨论】:

  • 好的,我想通了...我每次都需要初始化一个新的 NTDropDown(不要一遍又一遍地重复使用 tempDropDown)。所以,在我每次使用它之前添加tempDropDown = new NTDropDrop();。我应该删除这个问题吗?
  • 没有。留下问题。解决自己的问题对每个人仍然有用。

标签: c# list


【解决方案1】:

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

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

此外,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);
}

【讨论】:

    【解决方案2】:

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

    我很难弄清楚你到底想在列表中添加 tempDropDown 做什么。

    【讨论】:

    • 是的,我很困惑,因为它没有导致我的货运对象出现问题,但那是因为我每次迭代都从函数 readBaseFreight) 获取一个新对象...
    • 老实说,这不是我的主意...货运列表以 JSON 格式返回(将由应用程序使用),我被告知要创建一个单独的所有可能值列表对于每个运营商/模式,以便用户可以进一步过滤结果(如果他们愿意)......对我来说,唯一值列表将由应用程序创建......我应该只返回列表运费...但是...是的...
    猜你喜欢
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多