当前位置: 首页 > 编程语言 > C#

list.add好像是在添加对原对象的引用?分享

时间:2023-04-10 20:59:09 C#

list.add好像是在添加对原对象的引用?我创建了一些自定义类(NTDropDown和NTBaseFreight),用于存储从数据库检索的数据。我初始化NTBaseFreight列表和NTBaseFreight2列表。我可以使用List.Add成功地将商品添加到List.Add列表中,但是当我调试代码时,我的2个下拉列表仅包含1个NTDropDown,它始终与NTDropDown具有相同的值(我假设这是一个参考问题,但是我做错了什么?例如,在第二行,如果carrier和carrier_label是“001”、“MyTruckingCompany”,我在frt_carriers、frt_carriers和frt_modes的if语句上打断了它们。列表仅包含1具有相同值的项目“001”、“MyTruckingCompany”...“001”、“MyTruckingCompany”。代码:Listfrt_carriers=newList();列出frt_modes=newList();列出运费=newList();NTDropDowntempDropDown=newNTDropDown();NTBaseFreighttempFreight=newNTBaseFreight();//....从数据库中获取数据的代码...已删除while(myReader.Read()){tempFreight=readBaseFreight((IDataRecord)myReader);//检查承运人和模式是否在下拉列表中(如果不在则添加它们)tempDropDown.value=tempFreight.carrier;tempDropDown.label=tempFreight.carrier_label;如果(!frt_carriers.Contains(tempDropDown))frt_carriers.Add(tempDropDown);tempDropDown.value=tempFreight.mode;tempDropDown.label=tempFreight.mode_label;如果(!frt_modes.Contains(tempDropDown))frt_modes.Add(tempDropDown);//将运费添加到列表中freights.Add(tempFreight);}是的,引用类型列表实际上只是一个引用列表。您必须为要存储在列表中的每个对象创建一个新实例。此外,Contains方法比较引用,因此包含相同数据的两个对象不被视为相等。在列表的对象属性中查找值。如果(!frt_carriers.Any(c=>c.label==tempFreight.carrier_label)){NTDropDowntempDropDown=newNTDropDown{value=tempFreight.carrier,label=tempFreight.carrier_label};frt_carriers.Add(tempDropDown);}tempDropDown在整个循环中都是同一个对象。如果要添加多个实例,则需要为其创建一个新实例。我正在努力弄清楚您是如何尝试将tempDropDown添加到列表中的。以上是C#学习教程:list.add好像是添加对原对象的引用?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: