How to best implement Equals for custom types?

前端 未结 10 717
春和景丽
春和景丽 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: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);
            }
        }
    }
    

提交回复
热议问题