hashCode() method when equals() is based on multiple independent fields

前端 未结 10 2354
执念已碎
执念已碎 2021-02-08 09:16

i have a class whose equality is based on 2 fields such that if either one is equal then the objects of this type are considered equal. how can i write a hashCode() function for

10条回答
  •  没有蜡笔的小新
    2021-02-08 09:33

    How about this

    public override int GetHashCode()
    {
        return (id.ToString() + name.ToString()).GetHashCode();
    }
    

    The function should allways return a "valid" hash...

    Edit: just noticed that you use "or" not "and" :P well i doubt there is any good solution to this problem...

提交回复
热议问题