假设我们有以下DTO对象,它是数据库中记录的表示:
public class UserDto
{
public int Id { get; set; }
public DateTime? ExpireOn { get; set; }
}
所以Id
属性是不可为Null的,ExpireOn
是。我在实现基于Null对象模式的Domain对象时遇到了问题,因为我不知道如何实现不可为Null的ExpireOn
属性。做到这一点的最佳实用方法是什么?
我想出了这个解决方案:
public abstract class ExpirationTimeBase
{
public static ExpirationTimeBase NoExpiration = new NoExpirationTime();
public abstract bool IsExpired(DateTime now);
}
public class ExpirationTime : NoExpirationTime
{
public ExpirationTime(DateTime time) => Time = time;
public DateTime Time { get; }
public override bool IsExpired(DateTime now) => this.Time < now;
}
public class NoExpirationTime : ExpirationTimeBase
{
public override bool IsExpired(DateTime now) => false;
}
public class User
{
public User(string id, ExpirationTimeBase expireOn)
{
Id = id ?? throw new ArgumentNullException(nameof(id));
ExpireOn = expireOn ?? throw new ArgumentNullException(nameof(expireOn));
}
public string Id { get; set; }
public ExpirationTimeBase ExpireOn { get; set; }
}
问题是,情况是否会好转?
您可以在Ctor中使用Nullable并检查是否为null。
public class User
{
public User(int? id, Datetime? expireOn)
{
if(id == null)
{
throw new ArgumentNullException(nameof(id));
}
if(expireOn == null)
{
throw new ArgumentNullException(nameof(expireOn));
}
Id = id.Value
ExpireOn = expireOn.Value;
}
public int Id { get; set; }
public Datetime ExpireOn { get; set; }
}