C# - Generic HashCode implementation for classes

后端 未结 3 1346
独厮守ぢ
独厮守ぢ 2021-01-02 05:17

I\'m looking at how build the best HashCode for a class and I see some algorithms. I saw this one : Hash Code implementation, seems to be that .NET classes HashCode methods

3条回答
  •  猫巷女王i
    2021-01-02 05:33

    This is what I'm using:

    public static class ObjectExtensions
    {
        /// 
        /// Simplifies correctly calculating hash codes based upon
        /// Jon Skeet's answer here
        /// http://stackoverflow.com/a/263416
        /// 
        /// 
        /// Thunks that return all the members upon which
        /// the hash code should depend.
        /// 
        public static int CalculateHashCode(this object obj, params Func[] memberThunks)
        {
            // Overflow is okay; just wrap around
            unchecked
            {
                int hash = 5;
                foreach (var member in memberThunks)
                    hash = hash * 29 + member().GetHashCode();
                return hash;
            }
        }
    }
    
    
    

    Example usage:

    public class Exhibit
    {
        public virtual Document Document { get; set; }
        public virtual ExhibitType ExhibitType { get; set; }
    
        #region System.Object
        public override bool Equals(object obj)
        {
            return Equals(obj as Exhibit);
        }
    
        public bool Equals(Exhibit other)
        {
            return other != null &&
                Document.Equals(other.Document) &&
                ExhibitType.Equals(other.ExhibitType);
        }
    
        public override int GetHashCode()
        {
            return this.CalculateHashCode(
                () => Document, 
                () => ExhibitType);
        }
        #endregion
    }
    

    提交回复
    热议问题