C#中基于列表的属性的相等性

5

我已经阅读了许多与C#中适当的平等相关的文章:

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

如何重写 System.Object.GetHashCode 方法以获得最佳算法?

假设有以下示例类:

public class CustomData
{
    public string Name { get; set;}

    public IList<double> Values = new List<double>();
}

在使用.Equals()比较Values属性时,仍然是这种情况吗?下面是一个完整的相等性示例:

#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

我认为 other.Values.Equals(Values); 应该改为 other.Values.SequenceEqual(Values); - Sach
是的,这就是我对其进行更改的地方。 - Maximus
1个回答

3
List<T>.Equals(List<T> other) 方法将比较对象的引用。如果要通过属性 Values 定义相等为一致的 double 序列,请使用 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);
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接