不需要的对象 属性 在更改另一个对象时更改 属性 c#

unwanted object property changed when changing another object property c#

根据我在其他帖子中的理解,我知道我的对象在内存中使用相同的位置,但如何分离这些对象? 我尝试使用 new 但它不起作用或者我没有正确使用它。

注意 我没有在此处粘贴 setter 和 getter。

class Supermarket
{
    List<Product> _products = new List<Product>{ };
    List<Customer> _customers = new List<Customer>{ };
}

class Customer
{
    List<Product> _purchased= new List<Product>{ };
}
class Product
{
    string _id;
    string _name;
    DateTime _expireDate;
    int _cost;
    int _count;
}

我在一个方法中添加了一个 产品

Product product = new Product(...);
supermarket.Products.Add(product);

我想用另一种方法从 Supermarket.Products 复制 ProductSupermarket.Customers.Purchased。所以我想要一份,但我买不到。

这里我想制作复制但是它不起作用。

Product product = supermarket.Products[productIndex];
supermarket.Customers[customerIndex].Purchased.Add(product);

现在的问题是当我更改 Customer class 中的 Product 属性时,Product[= Supermarket 内的 39=] 属性也会更改。 例如

supermarket.Customers[customerIndex].Purchased.Last().Count = ...
//now the Product supermarket.Products[productIndex] will change too witch is unwanted

它不工作的原因是因为你正在做浅拷贝,只是将产品对象的指针添加到列表中,并非所有属性。所以如果你改变一个,另一个也会相应地受到影响。

您可以在 this answer 之后使用深层复制,但这样您必须将 class 标记为 [Serializable]。我认为最简单的方法是使用 Json 序列化程序:

public static class CloneHelper 
{
    public static T Clone<T>(T source)
    {
        var serialized = JsonConvert.SerializeObject(source);
        return JsonConvert.DeserializeObject<T>(serialized);
    }
}

var copyProduct = CloneHelper.Clone<Product>(product);

或者简单的,你可以像下面的代码一样自己管理,然后就可以了:

Product product = supermarket.Products[productIndex];

Product copyProduct = new Product() {
    Id = product.Id,
    Name = product.Name,
    ExpireDate = product.ExpireDate,
    Cost = product.Cost,
    Count = product.Count   
};

supermarket.Customers[customerIndex].Purchased.Add(copyProduct);