例如我有课
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
如何在此类中覆盖GetHashCode? p>
答案 0 :(得分:1)
您应该将对象的哈希码计算基于不可变字段,如果您可以使Person
的FirstName和LastName字段不可变,则可以使用基于Josh Bloch的以下模式&#39的建议:
public override int GetHashCode()
{
int hash = 17;
hash = hash * 31 + FirstName.GetHashCode();
hash = hash * 31 + LastName.GetHashCode();
return hash;
}
答案 1 :(得分:-1)
public override int GetHashCode()
{
return String.Concat(FirstName, LastName).GetHashCode();
}
答案 2 :(得分:-1)
您可以这样做:
public override int GetHashCode()
{
return FirstName.GetHashCode() ^ LastName.GetHashCode()
}
检查this了解更多