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;
}
}
real圣
9 years, 2 months ago
Answers
一般实现 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 9 years, 2 months ago