我们可以使用从WinForms控件继承的对象作为.NET Hashtable的键吗? [英] Can we use objects inherited from WinForms Control as keys of a .NET Hashtable?

查看:46
本文介绍了我们可以使用从WinForms控件继承的对象作为.NET Hashtable的键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用在DLL中实现的组件。它继承自System.Windows.Forms.Control。我们需要将其用作.NET Hashtable对象中的键。



MSDN状态


由以下对象用作键的对象必须使用哈希表才能覆盖Object.GetHashCode方法(或IHashCodeProvider接口)和Object.Equals方法(或IComparer接口)。


但是我们正在讨论的控件没有自己的GetHashCode方法实现。 Object.GetHashCode的文档告诉我们


如果未重写GetHashCode,则通过调用基类的Object.GetHashCode方法计算引用类型的哈希码,该方法将计算哈希码基于对象的引用


这是否意味着我们可以安全地在哈希表中按原样使用控件?

解决方案

执行此操作时,应该只关心对象标识。换句话说,您从不希望两个控件映射到同一哈希表插槽。从不精确到+/- 1%



Control类继承的默认Object.GetHashCode()和Object.Equals()实现已经很完美了,它们实现了对象引用



当然,您应该,Hashtable是8年前了。 p>

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?

解决方案

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.

这篇关于我们可以使用从WinForms控件继承的对象作为.NET Hashtable的键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆