[英]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.