【问题标题】:Check for identical objects [duplicate]检查相同的对象[重复]
【发布时间】:2021-10-24 12:12:31
【问题描述】:

我怎么不能检查对象是否相等? 我有 2 个类存储对象(带有类产品列表),我想找到共同产品,但是当我检查 Identical 2 个产品对象时,它们并不相同。

class Storage
    {
       public List<Product> many_product;
       public Storage(List<Product> el)
        {
            this.many_product.AddRange(el);
        }
        public static Storage mutual_products(Storage a, Storage b)
        {
            Storage mutal_products = new Storage();
            foreach (var prod in a.many_product)
                if (b.many_product.Contains(prod))// return false, but in list is a mutual product
                {
                    mutal_products.many_product.Add(prod);
                }
            return mutal_products;
        }
     }

当我用 if(prod1==prod2)//return false 检查相同的产品时也是如此

【问题讨论】:

  • “相同”表示这两个对象实际上是一个对象,可以用Object.ReferenceEquals(或者==,如果运算符没有重载)检查。

标签: c#


【解决方案1】:

您的产品类应实现IEquatable&lt;Product&gt; 接口,以便Contains 方法正常工作。例如:

public class Product : IEquatable<Product>
{
    public string Name { get; set; }

    public double Price { get; set; }

    public bool Equals(Product other)
    {
        return Name.Equals(other.Name)
            && Price.Equals(other.Price);
    }
}

如果您使用的是 .NET 5 和 C# 9,则可以将 Product 类设为 record。那么就不需要显式地实现IEquatable&lt;Product&gt;了。

【讨论】:

    【解决方案2】:

    有几种方法可以对对象进行深度比较(包括所有嵌套属性):使用反射、序列化等。 查看答案here了解详情

    为了自己的需要,写了自己的通用对象comparator

    【讨论】:

      猜你喜欢
      • 2018-01-07
      • 2020-07-09
      • 2016-02-23
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 2020-04-27
      • 2017-05-24
      相关资源
      最近更新 更多