定义一个底层的泛型

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);
        }
    }

 

posted @ 2013-05-29 11:47  haiziguo  阅读(389)  评论(0编辑  收藏  举报