unwanted object property changed when changing another object property c#

前端 未结 1 1352
别跟我提以往
别跟我提以往 2021-01-24 20:24

from what i understand in other posts i know that my objects use same place in memory but how to separate these objects? i tried to use new but it didn\'t work or i

相关标签:
1条回答
  • 2021-01-24 20:55

    The reason why it is not working is because you are doing shallow copy by just adding the pointer of product object into the list, not all properties. So if you change one, another will be affected accordingly.

    You can use deep copy following this answer, but this way you have to mark your class as [Serializable]. The simplest way which I think is to use Json serializer:

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

    Or simply, you can manage by yourself as the below code, then it works:

    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);
    
    0 讨论(0)
提交回复
热议问题