2012-11-07 32 views
5

我创建了一些自定义类(NTDropDownNTBaseFreight),用于存储从数据库中检索的数据。我初始化了NTBaseFreight列表和NTDropDown的2个列表。list.add似乎在添加对原始对象的引用?

我可以成功地使用List.Add到运费添加到列表运费,但我调试的代码,我2名下拉列表中只包含1 NTDropDown,它总是作为NTDropDown相同的值(我假设这是一个参考问题,但我做错了什么)?

举个例子,在第二行,如果承运人和carrier_label"001", "MyTruckingCompany",我把休息的if语句为frt_carriers,既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); 
} 
+2

好吧,我想通了......我需要每次初始化一个新的NTDropDown(不重复使用tempDropDown)。所以,在每次使用之前添加'tempDropDown = new NTDropDrop();'。我应该删除这个问题吗? –

+0

不可以。解决你自己的问题对每个人都是有用的。 – hometoast

回答

9

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

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

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

tempDropDown是在整个循环中的同一个对象。如果你想添加多个实例,你将需要创建一个新的实例。

我很难找出你想要添加tempDropDown的列表。

+0

是啊,我很困惑,因为它不会导致我的货物对象出现问题,但那是因为我从函数readBaseFreight获得了一个新的对象,每次迭代)... –

+0

说实话,这不是我的想法.. 。货物列表以JSON返回(它将被应用程序使用),我被告知为每个载体/模式创建一个单独的列表,列出所有可能的值,以便用户可以进一步过滤结果(如果他们想要的话) ...对我来说,这将是有道理的,唯一值的列表将由应用程序创建...我应该只是返回货物列表...但...是啊... –

相关问题