【发布时间】:2010-11-06 22:42:14
【问题描述】:
我遇到了 GetHashCode 和 Equals 的问题,我已经为一个类覆盖了这些问题。我正在使用运算符 == 来验证两者是否相等,如果它们的哈希码相同,我希望这将调用 GetHashCode 和 Equals 以验证它们确实相等。
但令我惊讶的是,两者都没有被调用并且相等测试的结果是错误的(虽然它实际上应该是真的)。
覆盖代码:
public class User : ActiveRecordBase<User>
[...]
public override int GetHashCode()
{
return Id;
}
public override bool Equals(object obj)
{
User user = (User)obj;
if (user == null)
{
return false;
}
return user.Id == Id;
}
}
平等检查:
if (x == y) // x and y are both of the same User class
// I'd expect this test to call both GetHashCode and Equals
【问题讨论】:
-
如果
==确实调用了您的Equals方法,那么它会导致堆栈溢出,因为它在对象上使用==运算符... -
您显示的代码中没有任何内容表明需要调用 GetHashCode()。仅当您将对象用作集合的键时才会调用它。