请阐述在领域驱动设计中,实体与值对象的等值性判断有何不同?举例说明。

在领域驱动设计(Domain-Drive Design, DDD)中,实体(Entity)和值对象(Value Object)是两个基本的概念,它们都有着自己独特的特点和使用场景。其中,实体拥有唯一标识符(通常是ID),其等值性基于这个唯一标识来判断,即使两个实体的其它属性完全相同,只要ID不同,它们就被认为是不同的实体;而值对象的等值性则基于其属性值进行判断,如果两个值对象的所有属性值都相等,则认为这两个对象相等。

实体示例:假设有一个Customer实体,它有CustomerId、Name等属性。即使两个Customer实体的Name都为“张三”,只要CustomerId不同,它们就代表两个不同的客户。

class Customer
{
    public Guid CustomerId { get; private set; }
    public string Name { get; private set; }

    public bool Equals(Customer other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return this.CustomerId.Equals(other.CustomerId);
    }
}

值对象示例:假设有一个Money值对象,它有Amount、Currency两个属性。如果两个Money对象的Amount和Currency都相同,则认为这两个对象相等。

class Money
{
    public decimal Amount { get; private set; }
    public string Currency { get; private set; }

    public bool Equals(Money other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return this.Amount == other.Amount && this.Currency == other.Currency;
    }
}

理解实体与值对象等值性判断的不同,对于正确地在领域模型中应用它们至关重要,有利于确保业务逻辑的正确性和软件系统的高质量构建。