public abstract class Entity<T> where T:Entity<T>
    {
        public Guid ID { get; private set; }
        public override bool Equals(object obj)
        {
            //第一个
            var other = obj as T;
            if (other == null) return false;
            //第二个
            var thisIsNew = Equals(ID, Guid.Empty);
            var otherIsNew = Equals(other.ID, Guid.Empty);
            if (thisIsNew && otherIsNew)
                return ReferenceEquals(this, other);
            //第三个
            return ID.Equals(other.ID);
        }
        private int? oldHashCode;
        public override int GetHashCode()
        {
            // once we have a hashcode we'll never change it
            if (oldHashCode.HasValue)
                return oldHashCode.Value;
            // when this instance is new we use the base hash code
            // and remember it, so an instance can NEVER change its
            // hash code.
            var thisIsNew = Equals(ID, Guid.Empty);
            if (thisIsNew)
            {
                oldHashCode = base.GetHashCode();
                return oldHashCode.Value;
            }
            return ID.GetHashCode();
        }

        public static bool operator ==(Entity<T> lhs, Entity<T> rhs)
        {
            return Equals(lhs, rhs);
        }
        public static bool operator !=(Entity<T> lhs, Entity<T> rhs)
        {
            return !Equals(lhs, rhs);
        }
    }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-05
  • 2021-10-08
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-25
  • 2021-06-25
  • 2021-10-25
  • 2022-01-07
  • 2022-12-23
相关资源
相似解决方案