How to best implement Equals for custom types?

前端 未结 10 640
春和景丽
春和景丽 2020-11-28 08:41

Say for a Point2 class, and the following Equals:

public override bool Equals ( object obj )

public bool Equals ( Point2 obj )

This is the

相关标签:
10条回答
  • 2020-11-28 09:20
    • Define what the identity means.. if reference identity then the default inherited equals will work.
    • If a value type (and thus value identity) you need to define.
    • If a class type, but has value semantics then define.

    Likely you want to both override Equals(object) and define Equals(MyType) because the latter avoids boxing. And override the equality operator.

    .NET Framework Guidelines book (2nd ed) has more coverage.

    0 讨论(0)
  • 2020-11-28 09:20

    Lie Daniel L said,

    public override bool Equals(object obj) {
        Point2 point = obj as Point2; // Point2? if Point2 is a struct
        return point != null && this.Equals(point);
    }
    
    public bool Equals(Point2 point) {
        ...
    }
    
    0 讨论(0)
  • 2020-11-28 09:24

    There is also a Fody plugin Equals.Fody that generates Equals() and GetHashCode() automatically

    0 讨论(0)
  • 2020-11-28 09:25

    The technique I've used that has worked for me is as follows. Note, I'm only comparing based on a single property (Id) rather that two values. Adjust as needed

    using System;
    namespace MyNameSpace
    {
        public class DomainEntity
        {
            public virtual int Id { get; set; }
    
            public override bool Equals(object other)
            {
                return Equals(other as DomainEntity);
            }
    
            public virtual bool Equals(DomainEntity other)
            {
                if (other == null) { return false; }
                if (object.ReferenceEquals(this, other)) { return true; }
                return this.Id == other.Id;
            }
    
            public override int GetHashCode()
            {
                return this.Id;
            }
    
            public static bool operator ==(DomainEntity item1, DomainEntity item2)
            {
                if (object.ReferenceEquals(item1, item2)) { return true; }
                if ((object)item1 == null || (object)item2 == null) { return false; }
                return item1.Id == item2.Id;
            }
    
            public static bool operator !=(DomainEntity item1, DomainEntity item2)
            {
                return !(item1 == item2);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题