在C#实现DDD实体类 [英] Implementing DDD Entity class in C#
本文介绍了在C#实现DDD实体类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我现在DDD开始,我已经找到了一个不错实施的ValueObject,但我似乎无法找到任何实体实施好,我想这将有一个ID一个通用的基实体类型(由需要规范)并实现当期的平等操作。
I'm now starting out on DDD, I've already found a nice implementation for ValueObject but I cant seem to find any good implementation for Entities, i want a generic base entity type which will have an ID(needed by the specification) and implement currect equality operations.
请告诉我最高贵的解决方案?
Whats the most elegent solution?
推荐答案
实体的唯一特性是,它具有长寿命和(半)永久性标识。您可以封装,并表示,通过实施 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
}
这篇关于在C#实现DDD实体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文