GetHashCode override of object containing generic array

前端 未结 9 1703
情歌与酒
情歌与酒 2020-12-04 05:35

I have a class that contains the following two properties:

public int Id      { get; private set; }
public T[] Values  { get; private set; }
<
9条回答
  •  情书的邮戳
    2020-12-04 05:56

    I know this thread is pretty old, but I wrote this method to allow me to calculate hashcodes of multiple objects. It's been very helpful for this very case. It's not perfect, but it does meet my needs and most likely yours too.

    I can't really take any credit for it. I got the concept from some of the .net gethashcode implementations. I'm using 419 (afterall, it's my favorite large prime), but you can choose just about any reasonable prime (not too small . . . not too large).

    So, here's how I get my hashcodes:

    using System.Collections.Generic;
    using System.Linq;
    
    public static class HashCodeCalculator
    {
        public static int CalculateHashCode(params object[] args)
        {
            return args.CalculateHashCode();
        }
    
        public static int CalculateHashCode(this IEnumerable args)
        {
            if (args == null)
                return new object().GetHashCode();
    
            unchecked
            {
                return args.Aggregate(0, (current, next) => (current*419) ^ (next ?? new object()).GetHashCode());
            }
        }
    }
    
        

    提交回复
    热议问题