使用中的GetHashCode重写等于测试平等 [英] Using GetHashCode to test equality in Equals override

查看:130
本文介绍了使用中的GetHashCode重写等于测试平等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是确定打电话的GetHashCode以从内部的Equals测试平等覆盖的方法?



例如,此代码可以接受的?

 公共类的Class1 
{
公共字符串中的
{
搞定;
组;
}

公共字符串B
{
获得;
组;
}

公众覆盖布尔等于(obj对象)
{
1级其他的obj = 1级为;
返回其他= NULL&放大器;!&安培; other.GetHashCode()== this.GetHashCode();
}

公共覆盖INT的GetHashCode()
{
INT结果= 0;
结果=(结果^ 397)^(A == NULL?0:A.GetHashCode());
结果=(结果^ 397)^(B == NULL?0:B.GetHashCode());
返回结果;
}
}


解决方案

的其他都是正确的;你平等的操作被打破了。为了说明:

 公共静态无效的主要()
{
变种C1 =新1级(){ A =apahaa,B = NULL};
变种C2 =新1级(){a =abacaz,B = NULL};
Console.WriteLine(c1.Equals(C2));
}



我想你想要的程序的输出是假的,但你平等的定义,它是在CLR的一些实现真。



记住,只有约四十亿可能的散列码。有这样超过四十亿可能的六个字母的字符串和因此,至少有两个人有相同的散列码。我展示你们两个;有无穷多。



在一般的,你可以期望,如果有N个可能的散列码然后让冲突上升显着,一旦你对自己在戏n个元素的平方根的几率。这就是所谓的生日悖论。对于我,为什么你不应该依靠平等的散列码的文章,请参阅:



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


Is it ok to call GetHashCode as a method to test equality from inside the Equals override?

For example, is this code acceptable?

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;
  }
}

解决方案

The others are right; your equality operation is broken. To illustrate:

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));
}

I imagine you want the output of that program to be "false" but with your definition of equality it is "true" on some implementations of the CLR.

Remember, there are only about four billion possible hash codes. There are way more than four billion possible six letter strings, and therefore at least two of them have the same hash code. I've shown you two; there are infinitely many more.

In general you can expect that if there are n possible hash codes then the odds of getting a collision rise dramatically once you have about the square root of n elements in play. This is the so-called "birthday paradox". For my article on why you shouldn't rely upon hash codes for equality, see:

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

这篇关于使用中的GetHashCode重写等于测试平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆