LCL有一个ValueObject<T>基类,它可以继承,以便容易地创建值对象类型。示例地址值对象类型::
public class Address : ValueObject<Address>
{
public Guid CityId { get; private set; } //A reference to a City entity.
public string Street { get; private set; }
public int Number { get; private set; }
public Address(Guid cityId, string street, int number)
{
CityId = cityId;
Street = street;
Number = number;
}
}
ValueObject基类覆盖相等操作符(和其他相关操作符和方法),以比较两个值对象,并假设所有属性都相同,它们是相同的。所有这些测试都通过了:
var address1 = new Address(new Guid("21C67A65-ED5A-4512-AA29-66308FAAB5AF"), "Baris Manco Street", 42);
var address2 = new Address(new Guid("21C67A65-ED5A-4512-AA29-66308FAAB5AF"), "Baris Manco Street", 42);
Assert.Equal(address1, address2);
Assert.Equal(address1.GetHashCode(), address2.GetHashCode());
Assert.True(address1 == address2);
Assert.False(address1 != address2);
即使它们在内存中是不同的对象,它们在我们的域是相同的。.
这里,一些用于值对象的最佳实践: