且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#实现DDD实体类

更新时间:2023-02-13 11:06:13

实体的唯一特性是,它具有长寿命和(半)永久性标识。您可以封装,并表示,通过实施 IEquatable< T> 。下面是做这件事:

The only characteristic of an Entity is that it has a long-lived and (semi-)permanent identity. You can encapsulate and express that by implementing IEquatable<T>. Here's one way to do it:

public abstract class Entity<TId> : IEquatable<Entity<TId>>
{
    private readonly TId id;

    protected Entity(TId id)
    {
        if (object.Equals(id, default(TId)))
        {
            throw new ArgumentException("The ID cannot be the default value.", "id");
        }

        this.id = id;
    }

    public TId Id
    {
        get { return this.id; }
    }

    public override bool Equals(object obj)
    {
        var entity = obj as Entity<TId>;
        if (entity != null)
        {
            return this.Equals(entity);
        }
        return base.Equals(obj);
    }

    public override int GetHashCode()
    {
        return this.Id.GetHashCode();
    }

    #region IEquatable<Entity> Members

    public bool Equals(Entity<TId> other)
    {
        if (other == null)
        {
            return false;
        }
        return this.Id.Equals(other.Id);
    }

    #endregion
}