简体   繁体   中英

What happens if a C# Dictionary has a 64-bit TKey on x86?

I'm reworking a few container classes from an old project of mine with (much more reusable) generic equivalents. I seem to have went out of my way years ago to ensure the TKey type for Dictionary was an int rather than my container's T type (which in this case, T is long ).

If I rewrite this to allow long to be used, what actually happens under-the-hood in the Dictionary class? Will it just forcefully hashcode the 64-bit value-type TKey into a 32-bit int? Perhaps something like this:

int hashKey32bit = tkey.GetHashCode();

The GetHashCode method always returns a 32 bit int , no matter what type or system you call it on. Thats the point of it and I don't see anything forcefully there. After all, there is no problem with using any object or struct of any size as key. (If they have a somewhat useful implementation of GetHashCode .)

The dictionary will probably end up with some collisions, but as long as the hash codes are distributed evenly across the 32 bit range thats fine.

Edit

So yes, the dictionary always calls the GetHashCode method, even for int , where it's rather simple:

public override int GetHashCode()
{
  return this;
}

For long ( int64 ) it looks like this:

public override int GetHashCode()
{
  return (int) this ^ (int) (this >> 32);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM