Billpeng Space

技术源自生活
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

重写Equals的方式

Posted on 2020-08-25 02:17  billpeng  阅读(215)  评论(0编辑  收藏  举报
        public override bool Equals(object obj)
        {
            //obj不为空
            if (obj == null)
                return false;
            //是否同一个引用
            if (ReferenceEquals(this, obj))
                return true;
            //是否不是聚合根
            IAggregateRoot ar = obj as IAggregateRoot;
            if (ar == null)
                return false;
            //是否不是同一个类型
            var thisType = this.GetType().Namespace.StartsWith("System.Data.Entity.Dynamic") ? this.GetType().BaseType : this.GetType();
            var objType = obj.GetType().Namespace.StartsWith("System.Data.Entity.Dynamic") ? obj.GetType().BaseType : obj.GetType();
            if (thisType != objType)
            {
                return false;
            }

            //Id是否相等
            return this.Id == ar.Id;
        }

        public override int GetHashCode()
        {
           var thisType = this.GetType().Namespace.StartsWith("System.Data.Entity.Dynamic") ? this.GetType().BaseType : this.GetType();
           string keyword = thisType.FullName + "|" + this.Id;
           return keyword.GetHashCode();
           //return this.Id.GetHashCode();
           //return base.GetHashCode();
        }