0

在我的应用程序中,我从数据库中检索 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#,并且很难找到问题的根源。

4

2 回答 2

2

This is because you're creating 1 instance of your Customer object, and adding it to the list 3 times (modifying it each time you loop).

If you move your new tracker.Customer() inside the loop, you'll create 3 individual customer objects.

于 2013-01-04T14:31:27.373 回答
1

您需要tracker.Customer在 for 循环的每次迭代中创建一个新实例,而不是循环外的单个实例:

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 中完全相同。

于 2013-01-04T14:28:58.947 回答