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

本文关键字:未知 窗体 应用程序 | 更新日期: 2023-09-27 17:50:34

我在几个属性中有一个类Product。问题是当我设置Product for Customer属性的Count时,Product for SupermarketCount也会被更改。

我有这些类和属性:

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;
}

通过调试,我发现这部分会改变超市产品计数,但我不明白为什么。

                supermarket.Customers[customerIndex].Purchaselist.Add(product);
                supermarket.Customers[customerIndex].Purchaselist.Last().Count=productCount;
超市产品Setter属性也被删除了,但是问题仍然存在。

添加产品我使用阀门(…),

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

每次向List中添加对象时,您都应该&;new&;(创建该对象的新实例),然后调用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

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

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