Overridding Equals and GetHash

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

    Here is how I would do it. Since it is common for two different people to have exactly the same name it makes more sense to use a unique identifier (which you already have).

    public class Person : IEquatable
    {
      public override int GetHashCode()
      {
        return PersonId.GetHashCode();
      }
    
      public override bool Equals(object obj)
      {
        var that = obj as Person;
        if (that != null)
        {
          return Equals(that);
        }
        return false;
      }
    
      public bool Equals(Person that)
      {
        return this.PersonId == that.PersonId;
      }
    }
    

    To answer your specific question: This only matters if you are using Person as a key in an IDictionary collection. For example, Dictionary or SortedDictionary, but not Dictionary.

提交回复
热议问题