我有下面的類IEquatables只稱爲如果基地的Equals實現覆蓋
class Product : IEquatable<Product>
{
public Guid Id { get; set; }
public bool Equals(Product other)
{
return Id.Equals(other.Id);
}
}
如果我試圖創建一個列表的項目的唯一列表如下
Guid a = Guid.NewGuid();
List<Product> listA = new List<Product>();
listA.Add(new Product(){Id = a});
List<Product> listB = new List<Product>();
listB.Add(new Product()
{
Id = a
});
Debug.Assert(listA.Union(listB).Count()==1);
兩個項目直到我覆蓋object.Equals方法,一旦我這樣做,我的代碼如下
class Product : IEquatable<Product>
{
public Guid Id { get; set; }
public bool Equals(Product other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Id.Equals(Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Product)) return false;
return Equals((Product) obj);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
我的IEquatable Equals方法現在被調用,但只有當我重寫基本方法,此外,如果我把對象等於方法斷點它永遠不會被調用。
這是爲什麼?
---- UPDATE
所以與產品類
class Product : IEquatable<Product>
{
public Guid Id
{
get;
set;
}
public bool Equals(Product other)
{
return Id.Equals(other.Id);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
如果GetHashCode的被刪除,IEquatable實施的Equals是從不打我明白你一般應當實現equals和GetHashCode在一起,是這是爲什麼?
將'GetHashCode'實現添加到您的原始類可以獲得您想要的行爲,它看起來像。 – AakashM