实现Equals和GetHashCode - 一种更简单的方法

时间:2018-06-16 07:02:05

标签: c# linq gethashcode iequatable

我有一个对象树(DTO),其中一个对象引用其他对象,依此类推:

class Person
{
    public int Id { get; }
    public Address Address { get; }
    // Several other properties
}

public Address
{
    public int Id { get; }
    public Location Location { get; }
    // Several other properties
}

这些对象可能非常复杂,并且具有许多其他属性。

在我的应用中,具有相同Person的{​​{1}}可以位于两个存储中,即应用中的本地存储,来自后端。我需要以特定的方式将在线Id与本地Person合并,因此我需要首先了解在线Person是否与本地存储的相同(换句话说)如果应用尚未更新本地Person

为了使用LINQ的Except,我知道我需要实现Person并且通常的方式我看到它是这样的:

Equatable<T>

对我而言,这听起来很复杂且难以维护,当属性发生变化时,很容易忘记更新class Person : IEquatable<Person> { public int Id { get; } public Address Address { get; } public override bool Equals(object obj) { return Equals(obj as Person); } public bool Equals(Person other) { return other != null && Id == other.Id && Address.Equals(other.Address); } public override int GetHashCode() { var hashCode = -306707981; hashCode = hashCode * -1521134295 + Id.GetHashCode(); hashCode = hashCode * -1521134295 + (Address != null ? Address.GetHashCode() : 0); return hashCode; } Equals。 取决于对象,它也可能有点计算成本。

以下不是一种更简单,更有效的方式来实施GetHashCodeEquals吗?

GethashCode

我的想法是,只要对象发生变化,就会有时间戳。 此时间戳与对象一起保存。 我想在存储中也使用此字段作为并发令牌。

由于DateTime的解决可能是一个问题,而不是使用时间,我认为Guid也是一个很好的选择,而不是DateTime。 没有太多的对象,因此Guid的独特性不应成为问题。

您认为此方法存在问题吗?

就像我上面所说的那样,我认为实现和运行起来比让Equals和GetHashCode覆盖所有属性要容易得多。

更新:我越想到它,我倾向于认为在课堂上实施class Person : IEquatable<Person> { public int Id { get; } public Address Address { get; private set; } public DateTime UpdatedAt { get; private set; } public void SetAdress(Address address) { Address = address; UpdatedAt = DateTime.Now; } public override bool Equals(object obj) { return Equals(obj as Person); } public bool Equals(Person other) { return other != null && Id == other.Id && UpdatedAt.Ticks == other.UpdatedAt.Ticks; } public override int GetHashCode() { var hashCode = -306707981; hashCode = hashCode * -1521134295 + Id.GetHashCode(); hashCode = hashCode * -1521134295 + UpdatedAt.Ticks.GetHashCode(); return hashCode; } } Equals并不是一个好方法。我认为最好实现一个专门的GetHashCode,它以特定的方式比较IEqualityComparer<Person>并将其传递给LINQ的方法。

原因是,与评论和答案一样,Person可以以不同的方式使用。

3 个答案:

答案 0 :(得分:1)

如果两个对象具有相同的属性但是在不同的时间创建,这会给你假阴性相等,如果两个对象是用不同的属性创建的,但是它们会相互一致(时钟不是准确的。)

对于LINQ Except,您需要实现GetHashCode,这应该使用所有属性的哈希码。

理想情况下,它们也应该是不可变的(删除私有setter),以便一个对象在其整个生命周期中具有相同的哈希代码。

您的GetHashCode也应为unchecked

或者,您可以将Except与自定义比较器一起使用。

答案 1 :(得分:1)

使用value-tuples(不为此分配)实现GetHashCode / Equals的真正懒惰版本:

class Person : IEquatable<Person>
{
    public int Id { get; }
    public Address Address { get; }
    public Person(int id, Address address) => (Id, Address) = (id, address);

    public override bool Equals(object obj) => Equals(obj as Person);

    public bool Equals(Person other) => other != null
             && (Id, Address).Equals((other.Id,other.Address));

    public override int GetHashCode() => (Id, Address).GetHashCode();
}

答案 2 :(得分:0)

以下是LinqPad草图,您可以从中开始。它拥有您可以使用的所有工具来根据您的需求进行定制。当然,这只是一个概念,并非所有方面都已完全阐述。

如您所见,有一个Include属性可以应用于您希望包含在哈希中的支持字段。

void Main()
{
    var o1 = new C { Interesting = "Whatever", NotSoInterresting = "Blah.." };
    var o2 = new C { Interesting = "Whatever", NotSoInterresting = "Blah-blah.." }; 

    (o1 == o2).Dump("o1 == o2"); // False
    (o2 == o1).Dump("o2 == o1"); // False

    var o3 = o1.Clone();
    (o3 == o1).Dump("o3 == o1"); // True
    (object.ReferenceEquals(o1, o3)).Dump("R(o3) == R(o2)"); // False

    o3.NotSoInterresting = "Changed!";
    (o1 == o3).Dump("o1 == C(o3)"); // True

    o3.Interesting = "Changed!";
    (o1 == o3).Dump("o1 == C(o3)"); // False
}

[AttributeUsage(AttributeTargets.Field)]
public class IncludeAttribute : Attribute { }

public static class ObjectExtensions
{
    public static int GetHash(this object obj) => obj?.GetHashCode() ?? 1;

    public static int CalculateHashFromFields(this object obj)
    {
        var fields = obj.GetType()
            .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly /*or not*/)
            .Where(f => f.CustomAttributes.Any(x => x.AttributeType.Equals(typeof(IncludeAttribute))));

        var result = 1;

        unchecked
        {
            foreach(var f in fields) result *= f.GetValue(obj).GetHash();
        }

        return result;
    }
}

public partial class C
{
    [Include]
    private int id;
    public int Id { get => id; private set { id = value; UpdateHash(); } }

    [Include]
    private string interesting;
    public string Interesting { get => interesting; set { interesting = value; UpdateHash(); } }

    public string NotSoInterresting { get; set; }
}

public partial class C: IEquatable<C>
{
    public C Clone() => new C { Id = this.Id, Interesting = this.Interesting, NotSoInterresting = this.NotSoInterresting };

    private static int _id = 1; // Some persistence is required instead

    public C()
    {
        Id = _id++;
    }

    private int hash;

    private void UpdateHash() => hash = this.CalculateHashFromFields();

    public override bool Equals(object obj)
    {
        return Equals(obj as C);
    }

    public bool Equals(C other) => this.hash == other.hash;

    public override int GetHashCode() => hash;

    public static bool operator ==(C obj1, C obj2) => obj1.Equals(obj2);

    public static bool operator !=(C obj1, C obj2) => !obj1.Equals(obj2);
}

[更新18.06.17]

更新版本:

void Main()
{
    var o1 = new C { Interesting = "Whatever", NotSoInterresting = "Blah.." };
    var o2 = new C { Interesting = "Whatever", NotSoInterresting = "Blah-blah.." }; 

    (o1 == o2).Dump("o1 == o2"); // False
    (o2 == o1).Dump("o2 == o1"); // False

    var o3 = o1.Clone();
    (o3 == o1).Dump("o3 == o1"); // True
    (object.ReferenceEquals(o1, o3)).Dump("R(o3) == R(o2)"); // False

    o3.NotSoInterresting = "Changed!";
    (o1 == o3).Dump("o1 == C(o3)"); // True

    o3.Interesting = "Changed!";
    (o1 == o3).Dump("o1 == C(o3)"); // False

    C o4 = null;
    (null == o4).Dump("o4 == null"); // True
}

[AttributeUsage(AttributeTargets.Field)]
public class IncludeAttribute : Attribute { }

public static class ObjectExtensions
{
    public static int GetHash(this object obj) => obj?.GetHashCode() ?? 1;
}

public abstract class EquatableBase : IEquatable<EquatableBase>
{
    private static FieldInfo[] fields = null;

    private void PrepareFields()
    {
        fields = this.GetType()
            .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly /*or not*/)
            .Where(f => f.CustomAttributes.Any(x => x.AttributeType.Equals(typeof(IncludeAttribute))))
            .ToArray();
    }

    private int CalculateHashFromProperties()
    {
        if (fields == null) PrepareFields();

        var result = 1;

        unchecked
        {
            foreach (var f in fields) result ^= f.GetValue(this).GetHash();
        }

        return result;
    }

    private bool CheckDeepEqualityTo(EquatableBase other)
    {
        if (ReferenceEquals(other, null) || other.GetType() != GetType()) return false;
        if (fields == null) PrepareFields();

        var result = true;
        for(int i = 0; i < fields.Length && result; i++)
        {
            var field = fields[i];
            result &= field.GetValue(this).Equals(field.GetValue(other));
        }
        return result;
    }

    private int hash;

    protected int UpdateHash() => hash = this.CalculateHashFromProperties();

    protected void InvalidateHash() => hash = 0;

    public override bool Equals(object obj) => Equals(obj as EquatableBase);

    public bool Equals(EquatableBase other) => object.ReferenceEquals(this, other) || this.CheckDeepEqualityTo(other);

    public override int GetHashCode() => hash == 0 ? UpdateHash() : hash;

    public static bool operator ==(EquatableBase obj1, EquatableBase obj2) => ReferenceEquals(obj1, obj2) || obj1?.CheckDeepEqualityTo(obj2) == true;

    public static bool operator !=(EquatableBase obj1, EquatableBase obj2) => !(obj1 == obj2);
}

public partial class C: EquatableBase
{
    private static int _id = 1; // Some persistence is required instead

    public C()
    {
        Id = _id++;
    }

    public C Clone() => new C { Id = this.Id, Interesting = this.Interesting, NotSoInterresting = this.NotSoInterresting };

    [Include]
    private int id;
    public int Id { get => id; private set { id = value; InvalidateHash(); } }

    [Include]
    private string interesting;
    public string Interesting { get => interesting; set { interesting = value; InvalidateHash(); } }

    public string NotSoInterresting { get; set; }
}

仍然无法摆脱在setter中调用某些东西(当然还有优化的地方),但这些改进很难:

  • 可重复使用的基类而不是部分
  • 感兴趣的字段按类型缓存
  • Hash仅在第一次请求失效后重新计算,并且无效是跛行
  • 根据感兴趣的字段进行深度相等检查,而不是仅仅比较哈希