在C#中GetHash code指引 [英] GetHashCode Guidelines in C#

查看:88
本文介绍了在C#中GetHash code指引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在本质C#3.0和.NET 3.5图书阅读:

I read in the Essential C# 3.0 and .NET 3.5 book that:

GetHash code()结束了一个特定的对象的生命周期回报率应该是   常数(相同值),即使该对象的数据的变化。在许多   的情况下,你应该缓存的方法返回强制执行这一点。

GetHashCode()’s returns over the life of a particular object should be constant (the same value), even if the object’s data changes. In many cases, you should cache the method return to enforce this.

这是一个有效的指导?

我已经试过内置的.NET类型一对夫妇和他们并没有这样的表现。

I have tried a couple built-in types in .NET and they didn't behave like this.

推荐答案

答案大多是,它是一个有效的准则,但也许不是一个有效的规则。它也不会告诉整个故事。

The answer is mostly, it is a valid guideline, but perhaps not a valid rule. It also doesn't tell the whole story.

而提出的一点是,对于可变类型,则无法立足散列code对可变数据,因为两个相等的对象必须返回相同的哈希code和哈希code已经是有效的为对象的生存期。如果散列code的变化,你结束了一个对象,迷失在散列集合,因为它不再生活在正确的散箱。

The point being made is that for mutable types, you cannot base the hash code on the mutable data because two equal objects must return the same hash code and the hash code has to be valid for the lifetime of the object. If the hash code changes, you end up with an object that gets lost in a hashed collection because it no longer lives in the correct hash bin.

例如,对象A返回1散列因此,它会在哈希表箱1。然后你改变一个对象,使其返回2的散列当一个哈希表去寻找它,它会在纸槽2并不能找到它 - 对象被孤立于斌1。这就是为什么哈希code,不得更改<打击>的对象的寿命,只有一个原因写入GetHash code实现是一个痛苦的对接。

For example, object A returns hash of 1. So, it goes in bin 1 of the hash table. Then you change object A such that it returns a hash of 2. When a hash table goes looking for it, it looks in bin 2 and can't find it - the object is orphaned in bin 1. This is why the hash code must not change for the lifetime of the object, and just one reason why writing GetHashCode implementations is a pain in the butt.

更新
埃里克利珀已经发布了博客上提供优秀的信息 GetHash code

Update
Eric Lippert has posted a blog that gives excellent information on GetHashCode.

其他更新
我做了一对夫妇的上述变化的:

Additional Update
I've made a couple of changes above:

  1. 在我做了指引和规则之间的区别。
  2. 在我打通过为对象的生命周期。

一个指引只是一个指导,而不是规则。在现实中, GetHash code 只有遵循这些原则,当事情希望效仿的对象的准则,当它被存储在一个哈希表等。如果你从来没有打算使用哈希表中的对象(或依赖于规则别的 GetHash code ),您的实现并不需要按照指导方针。

A guideline is just a guide, not a rule. In reality, GetHashCode only has to follow these guidelines when things expect the object to follow the guidelines, such as when it is being stored in a hash table. If you never intend to use your objects in hash tables (or anything else that relies on the rules of GetHashCode), your implementation doesn't need to follow the guidelines.

当你看到为对象的生命周期,你应该阅读为对象需要的时候合作,用哈希表或类似的。最喜欢的事情, GetHash code 即将知道何时打破规则。

When you see "for the lifetime of the object", you should read "for the time the object needs to co-operate with hash tables" or similar. Like most things, GetHashCode is about knowing when to break the rules.

这篇关于在C#中GetHash code指引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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