为该结构实现GetHashCode的正确方法 [英] Right way to implement GetHashCode for this struct

查看:72
本文介绍了为该结构实现GetHashCode的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个日期范围(从一个日期到另一个日期)作为字典的键,所以我写了自己的结构:

I want to use a date range (from one date to another date) as a key for a dictionary, so I wrote my own struct:

   struct DateRange
   {
      public DateTime Start;
      public DateTime End;

      public DateRange(DateTime start, DateTime end)
      {
         Start = start.Date;
         End = end.Date;
      }

      public override int GetHashCode()
      {
         // ???
      }
   }

实现GetHashCode的最佳方法是什么,以便没有两个不同范围的对象生成相同的哈希?我希望散列冲突尽可能少发生,尽管我理解Dictionary<>仍会检查我还将实现的相等运算符,但不想过多地污染示例代码.谢谢!

What's the best way to implement GetHashCode so no two objects of a differing range will generate the same hash? I want hash collisions to be as unlikely as possible, though I understand Dictionary<> will still check the equality operator which I will also implement, but didn't want to pollute the example code too much. Thanks!

推荐答案

您可以使用有效Java中的方法,因为Jon Skeet会显示

You can use the method from Effective Java as Jon Skeet shows here. For your specific type:

public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        hash = hash * 23 + Start.GetHashCode();
        hash = hash * 23 + End.GetHashCode();
        return hash;
    }
}

这篇关于为该结构实现GetHashCode的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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