是Object.GetHash code()唯一的参考或值? [英] Is Object.GetHashCode() unique to a reference or a value?

查看:207
本文介绍了是Object.GetHash code()唯一的参考或值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Object.GetHash $ MSDN文档C $ C()描述了方法应该是如何工作的3相矛盾的规则。

  1. 如果相同类型重新present两个对象相同的值,所述散列函数必须返回为两个对象相同的恒定值。
  2. 为了获得最佳性能,哈希函数必须生成一个随机分布于所有的输入。
  3. 的哈希函数必须不管返回所做到对象的任何变化完全相同的值。

规则1和; 3是矛盾的我。

难道Object.GetHash code()返回基于对象的一个唯一的号码,或在引用的对象。如果我覆盖的方法,我可以选择用什么,但我想知道什么是内部使用,如果有人知道。

解决方案
  

规则1和; 3是矛盾的我。

要在一定程度上,他们是。原因很简单:如果一个对象存储在一个哈希表,并通过改变它的价值,你改变它的哈希值,然后在哈希表已经失去了价值,你不能找到它再通过查询哈希表。虽然对象存储在哈希表中,它们保留它们的散列值是很重要的。

要实现这一点,往往是最简单的,以使哈希的对象不变,从而逃避问题的全部。然而足以使只有那些决定的散列值的字段不可变的。

请看下面的例子:

 结构的人{
    公共只读字符串名字;
    公共只读字符串名称;
    公共只读的DateTime生日;

    公众诠释ShoeSize;
}
 

人们很少改变他们的生日,大多数人永远不会改变自己的名字(结婚时除外)。然而,他们的鞋子大小可任意增加,甚至萎缩。因此,合理的确定使用他们的生日和名字,但不是他们的鞋码的人。哈希值应反映这一点:

 公众诠释GetHash code(){
    返回FirstName.GetHash code()^ Name.GetHash code()^ Birthday.GetHash code();
}
 

The MSDN documentation on Object.GetHashCode() describes 3 contradicting rules for how the method should work.

  1. If two objects of the same type represent the same value, the hash function must return the same constant value for either object.
  2. For the best performance, a hash function must generate a random distribution for all input.
  3. The hash function must return exactly the same value regardless of any changes that are made to the object.

Rules 1 & 3 are contradictory to me.

Does Object.GetHashCode() return a unique number based on the value of an object, or the reference to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows.

解决方案

Rules 1 & 3 are contradictory to me.

To a certain extent, they are. The reason is simple: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. It is important that while objects are stored in a hash table, they retain their hash value.

To realize this it is often simplest to make hashable objects immutable, thus evading the whole problem. It is however sufficient to make only those fields immutable that determine the hash value.

Consider the following example:

struct Person {
    public readonly string FirstName;
    public readonly string Name;
    public readonly DateTime Birthday;

    public int ShoeSize;
}

People rarely change their birthday and most people never change their name (except when marrying). However, their shoe size may grow arbitrarily, or even shrink. It is therefore reasonable to identify people using their birthday and name but not their shoe size. The hash value should reflect this:

public int GetHashCode() {
    return FirstName.GetHashCode() ^ Name.GetHashCode() ^ Birthday.GetHashCode();
}

这篇关于是Object.GetHash code()唯一的参考或值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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