我创建了一些自定义类(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