GetHashCode override of object containing generic array

前端 未结 9 1681
情歌与酒
情歌与酒 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:47

    How about something like:

        public override int GetHashCode()
        {
            int hash = Id;
            if (Values != null)
            {
                hash = (hash * 17) + Values.Length;
                foreach (T t in Values)
                {
                    hash *= 17;
                    if (t != null) hash = hash + t.GetHashCode();
                }
            }
            return hash;
        }
    

    This should be compatible with SequenceEqual, rather than doing a reference comparison on the array.

提交回复
热议问题