我創建了一些自定義類(NTDropDown
和NTBaseFreight
),用於存儲從數據庫中檢索的數據。我初始化了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);
}
好吧,我想通了......我需要每次初始化一個新的NTDropDown(不重複使用tempDropDown)。所以,在每次使用之前添加'tempDropDown = new NTDropDrop();'。我應該刪除這個問題嗎? –
不可以。解決你自己的問題對每個人都是有用的。 – hometoast