代码之家  ›  专栏  ›  技术社区  ›  Maximus

与基于列表的属性相等

  •  5
  • Maximus  · 技术社区  · 8 年前

    我读过很多关于C#中适当平等的文章:

    http://www.loganfranken.com/blog/687/overriding-equals-in-c-part-1/

    What is the best algorithm for an overridden System.Object.GetHashCode?

    public class CustomData
    {
        public string Name { get; set;}
    
        public IList<double> Values = new List<double>();
    }
    

    还是比较一下 价值观 使用属性 ? 这是一个完全平等的例子,我的意思是:

    #region Equality
    
        public override bool Equals(object value)
        {
            if(Object.ReferenceEquals(null, value)) return false;   // Is null?
            if (Object.ReferenceEquals(this, value)) return true;   // Is the same object?
            if (value.GetType() != this.GetType()) return false;    // Is the same type?
    
            return IsEqual((CustomData)value);
        }
    
        public bool Equals(CustomData obj)
        {
            if (Object.ReferenceEquals(null, obj)) return false;    // Is null?
            if (Object.ReferenceEquals(this, obj)) return true;     // Is the same object?
    
            return IsEqual(obj);
        }
    
        private bool IsEqual(CustomData obj)
        {
            return obj is CustomData other
                && other.Name.Equals(Name)
                && other.Values.Equals(Values);
        }
    
        public override int GetHashCode()
        {
            unchecked
            {
                // Choose large primes to avoid hashing collisions
                const int HashingBase = (int) 2166136261;
                const int HashingMultiplier = 16777619;
    
                int hash = HashingBase;
                hash = (hash * HashingMultiplier) ^ (!Object.ReferenceEquals(null, Name) ? Name.GetHashCode() : 0);
                hash = (hash * HashingMultiplier) ^ (!Object.ReferenceEquals(null, Values) ? Values.GetHashCode() : 0);
                return hash;
            }
        }
    
        public static bool operator ==(CustomData obj, CustomData other)
        {
            if (Object.ReferenceEquals(obj, other)) return true;
            if (Object.ReferenceEquals(null, obj)) return false;    // Ensure that "obj" isn't null
    
            return (obj.Equals(other));
        }
    
        public static bool operator !=(CustomData obj, CustomData other) => !(obj == other);
    
    #endregion
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   user8061994 user8061994    8 年前

    List<T>.Equals(List<T> other) 将比较引用。如果你想要财产平等 Values 定义为相同的序列 doubles ,使用 IEnumerable<TSource>.SequenceEqual.(IEnemerable<TSource> other) 方法( MSDN ). 查看您的 IsEqual(CustomData obj)

    private bool IsEqual(CustomData obj)
    {
        return obj is CustomData other
            && other.Name.Equals(Name)
            && other.Values.SequenceEqual(Values);
    }