c# – list.add似乎是在添加对原始对象的引用?
发布时间:2020-12-15 18:22:09 所属栏目:百科 来源:网络整理
导读:我创建了一些自定义类(NTDropDown和NTBaseFreight),我用它来存储从数据库中检索的数据.我初始化NTBaseFreight列表和NTDropDown的2个列表. 我可以成功使用List.Add将货物添加到货运列表中,但是当我调试代码时,我的2个下拉列表只包含1个NTDropDown,它总是与NTD
我创建了一些自定义类(NTDropDown和NTBaseFreight),我用它来存储从数据库中检索的数据.我初始化NTBaseFreight列表和NTDropDown的2个列表.
我可以成功使用List.Add将货物添加到货运列表中,但是当我调试代码时,我的2个下拉列表只包含1个NTDropDown,它总是与NTDropDown具有相同的值(我假设这是一个引用问题,但是我做错了什么? 举一个例子,在第二行,如果carrier和carrier_label是“001”,“MyTruckingCompany”并且我在frt_carriers的if语句上放了一个中断,frt_carriers和frt_modes在它们的列表中只包含1个项目,值“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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |