我目前对哈希集有疑问。我的类是不可变的并且只包含一个项目,当我将两个具有相同数据的不同类添加到哈希集中时,我会将它们都放在集合中。这很奇怪,因为我在基类和超类上都重载了 Equals 和 GetHashCode。
public abstract class Contact :IEquatable<Contact>
{
public readonly BigInteger Id;
public Contact(BigInteger id) { this.Id = id; }
public abstract bool Equals(Contact other);
public abstract int GetHashCode();
public abstract bool Equals(object obj);
}
和继承类:
public class KeyOnlyContact :Contact, IEquatable<KeyOnlyContact>
{
public KeyOnlyContact(BigInteger id) :base(id) { }
public override bool Equals(object obj)
{
if (obj is KeyOnlyContact)
return Equals(obj as KeyOnlyContact);
else if (obj is Contact)
return Equals(obj as Contact);
else
return (this as object).Equals(obj);
}
public override bool Equals(Contact other)
{
if (other is KeyOnlyContact)
return Equals(other as KeyOnlyContact);
else
return (this as object).Equals(other as object);
}
public bool Equals(KeyOnlyContact other)
{
return other.Id.Equals(Id);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
如您所见,所有真正的工作都被推迟到作为 id 的 BigInteger 上。这是一个 .net 类,我已经确认如果我只是将 BigInteger 添加到哈希集中,我不会重复。
澄清:
BigInteger a;
HashSet<Contact> set;
set.add(new KeyOnlyContact(a));
set.add(new KeyOnlyContact(a));
set.Count == 2