[英]Definition of GetHashCode() in C#
Dictionary
in C# uses GetHashCode() to retrieve hash code of a given key. C#中的
Dictionary
使用GetHashCode()检索给定键的哈希码。 I walk through whole of the Dictionary Class
, but there is not any definition for GetHashCode()
function. 我遍历了整个
Dictionary Class
,但是GetHashCode()
函数没有任何定义。 It is bothering me and I don't know how I can find definition of it in this class! 这困扰着我,我不知道如何在课堂上找到它的定义!
Assume I am using Dictionary<int,int> a = new Dictionary<int,int>()
, now what is the hash code of a given key in this structure? 假设我正在使用
Dictionary<int,int> a = new Dictionary<int,int>()
,那么此结构中给定键的哈希码是什么? (eg suppose this: a.Add(123,43)
. what is the hash code of this key, if number of buckets being 50) (例如,假设:
a.Add(123,43)
。如果存储桶数为50,则此密钥的哈希码是什么)
This is a part of Insert()
function of Dictionary class
. 这是
Dictionary class
的Insert()
函数的一部分。
private void Insert(TKey key, TValue value, bool add)
{
int freeList;
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (this.buckets == null)
{
this.Initialize(0);
}
int num = this.comparer.GetHashCode(key) & 0x7fffffff;
int index = num % this.buckets.Length;
If you don't specify an IEqualityComparer
, Dictionary
uses EqualityComparer<T>.Default
. 如果未指定
IEqualityComparer
,则Dictionary
使用EqualityComparer<T>.Default
。 This is a comparer that will just call object.GetHashCode
on the given argument. 这是一个比较器,它将仅在给定参数上调用
object.GetHashCode
。 So look at Int32.GetHashCode
. 因此,请看
Int32.GetHashCode
。
GetHashCode
is implemented on your TKey
type, not on the Dictionary
class. GetHashCode
是在您的TKey
类型上实现的,而不是在Dictionary
类上实现的。
For int.GetHashCode()
, which your example uses, it's defined as: 对于您的示例使用的
int.GetHashCode()
,其定义为:
public override int GetHashCode()
{
return this;
}
Number of backets has nothing to do with the hashcode value. backets的数量与哈希码值无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.