问题
We use a component implemented in a DLL. It is inherited from System.Windows.Forms.Control. We need to use it as keys in a .NET Hashtable object.
As MSDN states,
The objects used as keys by a Hashtable are required to override the Object.GetHashCode method (or the IHashCodeProvider interface) and the Object.Equals method (or the IComparer interface).
But the control we are talking about does not have its own implementation of the GetHashCode method. The documentation for Object.GetHashCode tells us that
If GetHashCode is not overridden, hash codes for reference types are computed by calling the Object.GetHashCode method of the base class, which computes a hash code based on an object's reference
Does it mean we can safely use the control "as is" in hashtables?
回答1:
You should only ever care for object identity when you do this. In other words, you would never want two controls to map to the same hash table slot. Never accurate to +/- 1%
The default Object.GetHashCode() and Object.Equals() implementations that the Control class inherits are already perfect, they implement object reference identity.
And of course you should Dictionary<Control, Something>
, Hashtable was 8 years ago.
来源:https://stackoverflow.com/questions/18059143/can-we-use-objects-inherited-from-winforms-control-as-keys-of-a-net-hashtable