GetHashCode()基于主键 - 是否安全?

boj*_*boj 3 .net c# hash

类具有ID属性,此属性从SQL表的主键列获取值.

如果我写的话,这是一个好习惯

public override int GetHashCode()
{
    return this.ID + GetType().GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)

进入我的班级?(等于已经以相同的方式覆盖了.)

Jon*_*eet 5

为什么要特别想在哈希码中包含类型?我可以看到,如果你在同一张地图中有很多不同类型的具有相同ID的对象,那将是多么有用,但通常我只是使用

public override int GetHashCode()
{
    return ID; // If ID is an int
    // return ID.GetHashCode(); // otherwise
}
Run Code Online (Sandbox Code Playgroud)

请注意,在继承层次结构中,相等的概念变得棘手 - 更喜欢组合而不是继承的另一个原因.你真的需要担心吗?如果您可以密封您的课程,它将使您更容易进行相等测试,因为您只需要编写:

public override bool Equals(object obj)
{
    MyType other = obj as other;
    return other != null && other.ID == ID;
}
Run Code Online (Sandbox Code Playgroud)

(您可能希望使用强类型的Equals方法并实现IEquatable.)