如何从重新实现 GetHashCode 的类中获取原始哈希码?
简短问题:如何获取已重新实现 GetHashCode()
的对象的 object.GetHashCode()
值?
长话短说: 所以我有大约十万个对象,每个对象共享许多(非编译时)公共字符串。常见的是如果值相等,则它是同一个实例。
知道了这一点,我想我宁愿使用标准对象比较(ReferenceEquals
),而不是完整的字符串比较 - 特别是因为这些比较是在字典中相当定期地查找的。
因此,我声明一个 class ReferenceEqualityComparer : IEqualityComparer
与 Dictionary
一起使用,认为无论如何它都会很有用,并尝试实现两种方法。
Equals 很简单,使用object.ReferenceEquals
。
但是如何获得与 GetHashCode
方法相同的 object.GetHashCode()
呢?
即如何获得对象实例的某种表示?
我知道还有其他方法可以做到这一点 - 创建一个 InternedString
类,它保存对 string
的引用,但不实现 Equals
> 或 GetHashCode
,或者为每个对象存储索引而不是字符串,但我现在很好奇 - 实际上是否有一种方法可以实现通用的 ReferenceEqualityComparer
?
Short question: How do I get the object.GetHashCode()
value for an object that has re-implemented GetHashCode()
?
Long story:
So I have about a hundred thousand objects, each sharing many (non-compile time) common strings. Common as in if the value is equal, it is the same instance.
Knowing that, I figure I'd rather use a standard object comparison (ReferenceEquals
) rather than a full string compare - particularly as these are looked up in dictionaries on a fairly regular basis.
So I declare a class ReferenceEqualityComparer : IEqualityComparer
to use with a Dictionary<string, TValue>
, figuring it'd be useful to have anyway, and go about trying to implement the two methods.
Equals is easy enough, use object.ReferenceEquals
.
But how do I get the equivalent of object.GetHashCode()
for the GetHashCode
method?
ie how do I get some representation of an object's instance?
I know there are other ways I can go about doing this - create an InternedString
class which holds a reference to the string
, but does not implement Equals
or GetHashCode
, or store indexes rather than strings with each object, but I'm now curious - is there actually a way to implement a generic ReferenceEqualityComparer
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看
RuntimeHelpers.GetHashCode(object)
。Have a look at
RuntimeHelpers.GetHashCode(object)
.