代码之家  ›  专栏  ›  技术社区  ›  Armbrat

使用GetHashCode测试Equals重写中的相等性

  •  9
  • Armbrat  · 技术社区  · 15 年前

    是否可以调用GetHashCode作为方法从Equals重写内部测试相等性?

    例如,这个代码可以接受吗?

    public class Class1
    {
      public string A
      {
        get;
        set;
      }
    
      public string B
      {
        get;
        set;
      }
    
      public override bool Equals(object obj)
      {
        Class1 other = obj as Class1;
        return other != null && other.GetHashCode() == this.GetHashCode();
      }
    
      public override int GetHashCode()
      {
        int result = 0;
        result = (result ^ 397) ^ (A == null ? 0 : A.GetHashCode());
        result = (result ^ 397) ^ (B == null ? 0 : B.GetHashCode());
        return result;
      }
    }
    
    8 回复  |  直到 12 年前
        1
  •  14
  •   Eric Lippert    15 年前

    public static void Main()
    {
        var c1 = new Class1() { A = "apahaa", B = null };
        var c2 = new Class1() { A = "abacaz", B = null };
        Console.WriteLine(c1.Equals(c2));
    }
    

    http://blogs.msdn.com/b/ericlippert/archive/2010/03/22/socks-birthdays-and-hash-collisions.aspx

        2
  •  7
  •   ulrichb    15 年前

    equality <=> hashcode equality

    equality => hashcode equality

    hashcode inequality => inequality

    http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx

        3
  •  2
  •   Dan Tao    15 年前

    Equals

        4
  •  1
  •   JaredPar    15 年前

    Equals true false

        5
  •  1
  •   Jim Mischel    15 年前

    GetHashCode

    public override bool Equals(object obj)
      {
        Class1 other = obj as Class1;
        if (other == null || other.GetHashCode() != this.GetHashCode())
            return false;
        // the hash codes are the same so you have to do a full object compare.
      }
    
        6
  •  1
  •   Gabe Timothy Khouri    15 年前

    GetHashCode Equals if (this.GetHashCode() != other.GetHashCode()) return false;

        7
  •  0
  •   Jon Hanna    15 年前

    GetHashCode()

    private bool IsMatch(KeyType newItem, KeyType storedItem, int newHash, int oldHash)
    {
      return ReferenceEquals(newItem, storedItem) // fast, false negatives, no false positives (only applicable to reference types)
        ||
        (
          newHash == oldHash // fast, false positives, no fast negatives
          &&
          _cmp.Equals(newItem, storedItem) // slow for some types, but always correct result.
        );
    }
    

    _cmp.Equals int

        8
  •  0
  •   nawfal Donny V.    12 年前
    1. GetHashCode

      if (other.GetHashCode() != this.GetHashCode()
          return false;
      

      Equals

    2. var watch = Stopwatch.StartNew();
      for (int i = 0; i < 100000; i++) 
      {
          action(); //Equals and GetHashCode called here to test for performance.
      }
      watch.Stop();
      Console.WriteLine(watch.Elapsed.TotalMilliseconds);