[英]New to programming and having a problem with List<T>
PAW.Btrieve oBtrieve = new PAW.Btrieve();
PAW.CustomerClass oCustomer = new PAW.CustomerClass();
int Status = oBtrieve.Connect("Z:\\payinc");
if (Status == 0)
{
GC.Collect();
Status = oCustomer.OpenFile();
if (Status == 0)
{
Status = oCustomer.GetFirst();
int cnt = oCustomer.RecordCount();
List<Customer> Custlist = new List<Customer>();
for (int i = 0; i < cnt; i++)
{
Custlist.Add(oCustomer);
oCustomer.GetNext();
}
GridView1.DataSource = Custlist;
GridView1.DataBind();
}
Status = oCustomer.CloseFile();
GC.Collect();
}
oBtrieve.Disconnect();
oBtrieve = null;
在此代码块的结尾,我有28个显示在数据网格中的最后一个客户的副本,而不是我想要看到的28个不同的客户。 有没有一种方法可以只存储来自oCustomer对象的数据,而不是对oCustomer对象的引用?
看起来您正在使用的特定API为它检索到的每个客户重复使用相同的CustomerClass实例:
oCustomer.GetNext();
因此,每次将oCustomer添加到列表时,都将添加相同的实例,对“ GetNext”的调用会更改该实例的属性。
我建议将oCustomer的各个属性复制到该类的新实例中,并将其添加到列表中。 也许像这样:
Custlist.Add(new CustomerClass
{
// obviously I don't know what the properties of
// CustomerClass are, so humour me.
Name = oCustomer.Name,
Address = oCustomer.Address,
Phone = oCustomer.Phone
});
这样,您每次都将一个不同的客户实例添加到列表中。
您正在为每个客户添加oCustomer
。 您应该使用迭代器i
来访问oCustomer中的(我认为是)集合。
我不确定您的课程结构是什么,但是
for (int i = 0; i < cnt; i++)
{
Custlist.Add(oCustomer);
oCustomer.GetNext();
}
应该:
for (int i = 0; i < cnt; i++)
{
Custlist.Add(oCustomer[i]);
oCustomer.GetNext();
}
另外,不要使用GC.Collect()
。 那只是自找麻烦。
我猜这是因为PAW.CustomerClass是引用类型,而CustomerClass.GetNext()会将下一项读入现有对象中……而不创建新项。
每次将对象添加到列表时,它都会添加对对象的引用,而不是对象的副本。 这意味着当您在将对象添加到列表后更新对象的值时,列表中的对象将反映这些更改...并且由于GetNext()每次迭代都对同一对象进行了这些更改,因此列表中有29个引用SAME CustomerClass对象。
您可以尝试更改以下行:
Custlist.Add(oCustomer);
至
// assuming a shallow copy will work for this object
Custlist.Add(oCustomer.MemberwiseClone());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.