c# .net Equals()函数重载, 像下面这样写好吗?


帮忙评审一下下面这个写法


 class Product
    {
        public string Name;
        public DateTime ExpiryDate;
        public decimal Price;
        public string[] Sizes;

        public override bool Equals(object obj)
        {
            Product p2 = (Product)obj;
            if (Name == p2.Name && ExpiryDate == p2.ExpiryDate && Price == p2.Price)
            {
                for (int i = 0; i < Sizes.Length; i++)
                {
                    if (!Sizes[i].Equals(p2.Sizes[i]))
                        return false;
                }
                return true;
            }
            else
                return true;
        }


    }

c# .net hash_equals

real圣 8 years, 7 months ago

一般实现 Equals 要同步实现 GetHashCode() 用于快速比较


 // 示例
    public override int GetHashCode() {
        var hash = Name == null ? 0 : Name.GetHashCode();
        hash <<= 7;
        hash |= ExpiryDate.GetHashCode();
        hash <<= 7;
        hash |= Price.GetHashCode();
        hash <<= 7;
        if (Sizes != null) {
            hash | Sizes.GetHashCode();
        }
        return hash;       
    }

Equals 的部分基本上没有问题,但是如果传入的为是 Produce 对象会抛异常,应该用 obj as Product 代替 (Product) obj 。另外在流程上作少许变更可以更清晰


 public override bool Equals(object obj) {
        Product p2 = obj as Product;
        if (p2 == null) {
            return false;
        }

        if (Name != p2.Name || ExpiryDate != p2.ExpiryDate || Price != p2.Price) {
            return false;
        }

        if (Sizes == null && p2.Sizes == null) {
            return true;
        }

        return Sizes.Equals(p2.Sizes);
    }

fy answered 8 years, 7 months ago

先判断 obj is Product ,以避免 obj 不是 Product 的情况。

另外,可以把两个 Product 比较的逻辑放在双等运算符重载里面, Equals 中调用。

具体逻辑没有什么统一的标准,比如你可以比较所有字段,也可以在有 id 的情况只比较 id ,因业务而异。

蛋疼D牛牛 answered 8 years, 7 months ago

Your Answer