C# windows 窗体应用程序中的未知行为

unknown behaviour in C# windows form application

我在几个属性中有一个 class Product。 问题是当我为 Customer 属性 设置 ProductCount 时 [= SupermarketProduct 的 23=]Count 也会更改。

我有这些 classes 和属性:

class Supermarket
{
    string _name;
    string _address;
    string _phoneNumber;
    List<Product> _products = new List<Product>{ };
    List<Product> _soldProducts = new List<Product>{ };
    List<Customer> _customers = new List<Customer>{ };
    private int _customersCount = 0;
 }

class Customer:Human
{
    int _customerId;
    string _bankId;
    List<Product> _purchased = new List<Product> { };
    List<Product> _purchaselist = new List<Product> { };
    float _discount;
}

class Product
{
    string _id;
    string _name;
    DateTime _expireDate;
    int _cost;
    int _count;
}

通过调试我发现这部分会改变 SupermarketProductCount ] 但是我不明白为什么。

                supermarket.Customers[customerIndex].Purchaselist.Add(product);
                supermarket.Customers[customerIndex].Purchaselist.Last().Count=productCount;

我还删除了 Setter 属性 的 Products in Supermarket 但问题依然存在

用于添加我使用的产品 .Add(...);

我假设您在 supermarket.Customerssupermarket.Supermarket 中使用相同的 Product class 实例。

确保在将产品添加到购买列表时创建 Product 的新实例

每次将对象添加到列表中时,您都应该在调用 Add() 方法之前“新建”(创建新实例)该对象。

Product product = new Product();
product._id="original value";
productList1.Add(product);
productList2.Add(product);

product._id="new value"; // this will change both object instances that you have added to the 2 lists above.

另一个例子:

   Product product = new Product();
   for(int i=0;i<3;i++){
       product._id=i.ToString();
       productList.Add(product);
   }
   //EXPECTED: 0 1 2
   //RESULT: 2 2 2

相反,您应该这样做:

更新

        Product product = new Product();
        product._id = "fisrt value";

        List<Product> productList1 = new List<Product>();
        List<Product> productList2 = new List<Product>();

        productList1.Add(product);
        product = new Product(); // initialize a new instance
        product._id = "second value";
        productList2.Add(product);

        product = new Product();// initialize another new instance
        product._id = "new value";

        Console.WriteLine("List 1:");
        foreach (var p in productList1)
        {
            Console.WriteLine(p._id + " ");
        }

        Console.WriteLine("List 2:");

        foreach (var p in productList2)
        {
            Console.WriteLine(p._id + " ");
        }

        Console.WriteLine("Last value: " + product._id);

        Console.ReadKey();

      //RESULT: List1: first value
      //        List2: second value
      //        Last value: new value