【问题标题】:unwanted object property changed when changing another object property c#更改另一个对象属性时更改了不需要的对象属性c#
【发布时间】:2015-05-25 18:43:55
【问题描述】:

根据我在其他帖子中的理解,我知道我的对象在内存中使用相同的位置,但是如何分离这些对象? 我尝试使用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 类中的 Product 属性时,Supermarket 中的 Product 属性将会改变也。 例如

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

【问题讨论】:

  • 我不知道什么是克隆。我真的是 C# 和面向对象语言的新手……你能告诉我我应该用简单的方式写什么吗? @CuongLe
  • 你的 Product 类是什么样子的?
  • 在这里我更新了我的帖子。我没有粘贴所有代码。 product 像往常一样具有 setter 和 getter 以及一个构造函数。 @CuongLe

标签: c# object properties copy instance


【解决方案1】:

它不起作用的原因是因为您只是通过将产品对象的指针添加到列表中而不是所有属性来进行浅复制。所以如果你改变一个,另一个就会受到相应的影响。

您可以在this answer 之后使用深拷贝,但这样您必须将您的课程标记为[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);

【讨论】:

  • 这里没有发生浅拷贝。他只是传递对象引用。
猜你喜欢
  • 1970-01-01
  • 2020-11-06
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多