Right way to implement GetHashCode for this struct

前端 未结 7 1874
庸人自扰
庸人自扰 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 07:00

    Combining Jon Skeet's answer and comment on the question (so please, no voting on this, just consolidating):

    struct DateRange
    {
        private readonly DateTime start;
    
        private readonly DateTime end;
    
        public DateRange(DateTime start, DateTime end)
        {
            this.start = start.Date;
            this.end = end.Date;
        }
    
        public DateTime Start
        {
            get
            {
                return this.start;
            }
        }
    
        public DateTime End
        {
            get
            {
                return this.end;
            }
        }
    
        public static bool operator ==(DateRange dateRange1, DateRange dateRange2)
        {
            return dateRange1.Equals(dateRange2);
        }
    
        public static bool operator !=(DateRange dateRange1, DateRange dateRange2)
        {
            return !dateRange1.Equals(dateRange2);
        }
    
        public override int GetHashCode()
        {
            // Overflow is fine, just wrap
            unchecked
            {
                var hash = 17;
    
                // Suitable nullity checks etc, of course :)
                hash = (23 * hash) + this.start.GetHashCode();
                hash = (23 * hash) + this.end.GetHashCode();
                return hash;
            }
        }
    
        public override bool Equals(object obj)
        {
            return (obj is DateRange)
                && this.start.Equals(((DateRange)obj).Start)
                && this.end.Equals(((DateRange)obj).End);
        }
    }
    
    0 讨论(0)
提交回复
热议问题