list.add似乎要添加对原始对象的引用? [英] list.add seems to be adding a reference to the original object?

查看:274
本文介绍了list.add似乎要添加对原始对象的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我可以成功地使用List.Add将货运添加到货运清单中,但是在调试代码时,我的2个下拉列表仅包含1个NTDropDown,其值始终与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)?

举个例子,在第二行,如果载波和carrier_label"001", "MyTruckingCompany",并且我在frt_carriers的if语句上放了一个空格,则frt_carriers和frt_modes在它们的列表中将只包含1个项目. ,值为"001", "MyTruckingCompany" ... NTDropDown中的相同值.

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.

代码:

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

推荐答案

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

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.

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

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

这篇关于list.add似乎要添加对原始对象的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆