Overridding Equals and GetHash

后端 未结 4 1732
既然无缘
既然无缘 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:13

    Your GetHashCode() and Equals() methods should look like this:

    public int GetHashCode()
    {
        return (FirstName.GetHashCode()+1) ^ (LastName.GetHashCode()+2);
    }
    
    
    public bool Equals(Object obj)
    {
        Person p = obj as Person;
    
        if (p == null) 
            return false;
    
        return this.Firstname == p.FirstName && this.LastName == p.Lastname;
    }
    

    The rule is that GetHashCode() must use exactly the fields used in determining equality for the .Equals() method.

    As for the dictionary part of your question, .GetHashCode() is used for determining the key in a dictionary. However, this has a different impact for each of the dictionarys in your question.

    The dictionary with the int key (presumably your person ID) will use the GetHashCode() for the integer, while the other dictionary (ObjDic) will use the GetHashCode() from your Person object. Therefore PKDic will always differentiate between two people with different IDs, while ObjDic might treat two people with different IDs but the same first and last names as the same record.

提交回复
热议问题