c# How to find if two objects are equal

前端 未结 6 1970
北荒
北荒 2020-12-08 02:40

I want to know the best way to compare two objects and to find out if they\'re equal. I\'m overriding both GethashCode and Equals. So a basic class looks like:



        
6条回答
  •  情歌与酒
    2020-12-08 03:17

    Your current equality method is broken - there are more values than possible hash codes. It's entirely reasonable (and expected) that you will occasionally have values which are unequal but give the same hash. Equals should check the actual values:

    public override bool Equals(object obj)
    {
        Test test = obj as Test;
        if (obj == null)
        {
            return false;
        }
        return Value == test.Value &&
            String1 == test.String1 &&
            String2 == test.String2;
    }
    

    A few things to note:

    • Your way of generating the hashcode will give the same value for any fixed Value if String1 and String2 are the same; it will also blow up if String1 or String2 is null. This is an unfortunate aspect of using XOR for hashing. I prefer something like this:

      // Put this extension method in a utility class somewhere
      public static int SafeGetHashCode(this T value) where T : class
      {
          return value == null ? 0 : value.GetHashCode();
      }
      
      // and this in your actual class
      public override int GetHashCode()
      {
          int hash = 19;
          hash = hash * 31 + Value;
          hash = hash * 31 + String1.SafeGetHashCode();
          hash = hash * 31 + String2.SafeGetHashCode();
          return hash;
      }
      
    • Generally speaking, equality becomes tricky when inheritance gets involved. You may want to consider sealing your class.

    • You may also want to implement IEquatable

提交回复
热议问题