Overridding Equals and GetHash

后端 未结 4 1730
既然无缘
既然无缘 2021-01-13 09:39

I have read that when you override Equals on an class/object you need to override GetHashCode.

 public class Person : IEquatable
    {
                 


        
4条回答
  •  礼貌的吻别
    2021-01-13 10:17

    You should always override GetHashCode.

    A Dictionary will function without GetHashCode, but as soon as you call LINQ methods like Distinct or GroupBy, it will stop working.

    Note, by the way, that you haven't actually overridden Equals either. The IEquatable.Equals method is not the same as the virtual bool Equals(object obj) inherited from Object. Although the default IEqualityComparer will use the IEquatable interface if the class implements it, you should still override Equals, because other code might not.

    In your case, you should override Equals and GetHashCode like this:

    public override bool Equals(object obj) { return Equals(obj as Person); }
    public override int GetHashCode() {
        return FirstName.GetHashCode() ^ LastName.GetHashCode();
    }
    

提交回复
热议问题