私のアプリでは、データベースから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#を使用せざるを得なくなり、問題の原因を見つけるのに本当に苦労しています。