使用继承的定制对象的数组列表
本文关键字:对象 数组 列表 继承 | 更新日期: 2023-09-27 17:50:50
在我的应用程序中,我从数据库中检索3行数据,我循环遍历数据行以将数据分配给我的客户对象,然后将客户添加到客户集合:
// new customer object to fill in loop and assign to collection
tracker.Customer myCustomer = new tracker.Customer();
// new customer collection object to fill later
Tracker.customerCollection myCustomerCollection = new trackerCustomerCollection();
foreach (System.Data.DataRow drRow in dsResults.Tables[0].Rows)
{
myCustomer.CustomerID = Item["CustomerID"];
myCustomer.FKBandID = Convert.ToInt32(drRow["FKBandID"]);
myCustomer.FKSectorID = Convert.ToInt32(drRow["FKSectorID"]);
myCustomer.CustomerName = Convert.ToString(drRow["CustomerName"]);
myCustomer.CustomerAddress = Convert.ToString(drRow["CustomerAddress"]);
myCustomer.CustomerPhoneNumber = Convert.ToString(drRow["CustomerPhoneNumber"]);
myCustomerCollection.Add(myCustomer);
}
问题是,当我尝试使用填充的myCustomerCollection
时,集合中的3个Customer
对象都是相同的。当我在循环中迭代时,myCustomer
的每个实例都是不同的,但是一旦添加到myCustomerCollection
,它们就会改变。每一项都与上一项相同。
如果有人能给我指出正确的方向,我将非常感激,我已经在VB中使用了这个原则。. NET没有任何问题,但我现在被迫使用c#,并有真正的麻烦找到我的问题的根源。
这是因为您创建了一个Customer
对象的实例,并将其添加到列表中3次(每次循环时修改它)。
如果您将new tracker.Customer()
移动到循环中,您将创建3个单独的客户对象。
您需要在for循环的每次迭代中创建一个新的tracker.Customer
,而不是在循环外创建一个单独的实例:
foreach (var drRow in dsResults.Tables[0].Rows)
{
// Create a brand new instance of a customer and set its properties
var myCustomer = new tracker.Customer()
{
CustomerID = Item["CustomerID"];
FKBandID = Convert.ToInt32(drRow["FKBandID"]);
FKSectorID = Convert.ToInt32(drRow["FKSectorID"]);
CustomerName = Convert.ToString(drRow["CustomerName"]);
CustomerAddress = Convert.ToString(drRow["CustomerAddress"]);
CustomerPhoneNumber = Convert.ToString(drRow["CustomerPhoneNumber"])
};
// Add your new customer to the customer collection
myCustomerCollection.Add(myCustomer);
}
现在发生的事情是你的myCustomerCollection
包含三个引用到同一个myCustomer
实例,因为你没有为数据库中的每条记录实例化一个new
。您现在在myCustomer
中看到的值可能属于数据的最后一行。
通过在for循环的每次迭代中创建一个新实例,您将在列表中拥有三个不同的tracker.Customer
对象。
此行为在VB.NET中是完全相同的。