Right way to implement GetHashCode for this struct

前端 未结 7 1878
庸人自扰
庸人自扰 2021-02-13 06:13

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 St         


        
7条回答
  •  名媛妹妹
    2021-02-13 06:56

    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;
        }
    }
    

提交回复
热议问题