English 中文(简体)
能够自定义 GetHashcode 执行对词典或 Hashbable s “ bucket” 产生问题吗?
原标题:Can a custom GetHashcode implementation cause problems with Dictionary or Hashtable s "buckets"

我正在考虑对给定对象实施我自己的自定义散列码..., 并将其作为我的字典的 < code> keys 。 因为两个对象可能有相同的散列码( 可能), 还有什么其他操作员应该由我取代, 而这个( 概念上的) 取代应该是什么样子?

   myDictionary.Add(myObj.GetHashCode(),myObj);

Vs 和

   myDictionary.Add(myObj,myObj);

换句话说,词典是否使用下列组合来确定独特性和放置物体的桶子?

哪些比其他人更重要?

  • HashCode
  • Equals
  • ==
  • CompareTo()

比较是否只与分类词汇中需要的比较?

问题回答

GetHashCode 用于什么?

设计上它只对一件事有用: 将对象放入散列桌上。 因此名称 。

GetHashCode 设计只能做一件事: 平衡散列表。 不要将它用于其他任何用途。 特别是 :

  • It does not provide a unique key for an object; probability of collision is extremely high.
  • It is not of cryptographic strength, so do not use it as part of a digital signature or as a password equivalent
  • It does not necessarily have the error-detection properties needed for checksums.

诸如此类。

埃里克·利波特

http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/

它不是造成问题的桶—— 它实际上是在您使用散列码确定桶后找到正确的物体实例。 既然桶内所有物体都使用相同的散列码, 则使用目标平等( Equals )来找到正确的物体。 规则是, 如果两个物体被认为相等, 它们应该产生相同的散列码 - 但产生相同散列码的两个物体可能不相等 。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签