在不可变类型的构造函数中生成HashCode [英] Generate HashCode in constructor of immutable type

查看:169
本文介绍了在不可变类型的构造函数中生成HashCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对不可变类型的HashCode有一些疑问。

i have some questions about the HashCode of immutable types.


  • 我可以预生成不可变类型的HashCode构造函数还是有什么理由不这样做?

  • 是否应该在调用方法GetHashCode()时再次生成Hashcode?

这里有一个示例类:

    public class Id  {

        private readonly object _value;

        private readonly int _hash = -1;


        public Id( object value ) {
          _value = value;
          _hash = ( int ) ( 7 * value.GetType().GetHashCode() + 7 + 7 * _value.GetHashCode() );
        }

        public object Value {
          get {
            return _value;
          }
        }

        public override int GetHashCode() {
          return _hash;
        }

        public override bool Equals( object obj ) {
          Id other = obj as Id;

          if ( other == null ) {
            return false;
          }

          return this.GetHashCode() == other.GetHashCode();
        }
        }


推荐答案

可能预生成哈希码但是为什么?只要在需要时产生它(在 GetHashCode ),然后可能存储它 - 大多数对象从来不需要有一个哈希,所以它只会减慢程序。

You may pregenerate the hashcode but why? Just generate it when needed (in GetHashCode) and then maybe store it - Most objects are never required to have a hash so it would just slow down the programm.


当调用方法GetHashCode()时,我应该再次生成Hashcode吗?

Should i always generate the Hashcode again, when the method GetHashCode() is called?

不可变对象的哈希码应该始终是相同的,所以它不应该有任何效果,无论是再次生成它还是存储它,除非存储增加性能。

The hashcode of an immutable object should always be the same so it shouldn't have any effect whether you generate it again or store it except that storing increases the performance.

注意:你不能通过比较HashCodes来定义 Equals - 两个不同的对象可以具有相等的HashCodes 。

Note: You shouln't define Equals by comparing HashCodes - Two different object may have equal HashCodes (hash collsion).

这篇关于在不可变类型的构造函数中生成HashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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