相同的GetHashCode()用于不同的对象 [英] Same GetHashCode() for different objects
本文介绍了相同的GetHashCode()用于不同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
执行这段代码后:
int a = 50;
float b = 50.0f;
Console.WriteLine(a.GetHashCode() == b.GetHashCode());
我们得到False
,这是预期的,因为我们正在处理不同的对象,因此我们应该获得不同的哈希值.
We get False
, which is expected, since we are dealing with different objects, hence we should get different hashes.
但是,如果我们执行此操作:
However, if we execute this:
int a = 0;
float b = 0.0f;
Console.WriteLine(a.GetHashCode() == b.GetHashCode());
我们得到True
.两个对象都返回相同的哈希码:0
.
We get True
. Both obejcts return the same hash code: 0
.
为什么会这样?他们不应该返回不同的哈希值吗?
Why does this happen? Aren't they supposed to return different hashes?
推荐答案
System.Int32
的GetHashCode
类似于:
public override int GetHashCode()
{
return this;
}
当然是0
,它将返回0
.
System.Single
的(float
是别名)GetHashCode
是:
public unsafe override int GetHashCode()
{
float num = this;
if (num == 0f)
{
return 0;
}
return *(int*)(&num);
}
就像您看到的那样,在0f
它将返回0
.
Like you see, at 0f
it will return 0
.
使用的程序是ILSpy.
Program used is ILSpy.
这篇关于相同的GetHashCode()用于不同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文