Can we use objects inherited from WinForms Control as keys of a .NET Hashtable?

我的未来我决定 提交于 2019-12-24 18:17:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!