2012-11-07 44 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返回(它將被應用程序使用),我被告知爲每個載體/模式創建一個單獨的列表,列出所有可能的值,以便用戶可以進一步過濾結果(如果他們想要的話) ...對我來說,這將是有道理的,唯一值的列表將由應用程序創建...我應該只是返回貨物列表...但...是啊... –

相關問題