0

假设我们有以下 DTO 对象,它表示数据库中的记录:

public class UserDto
{
  public int Id { get; set; }  
  public DateTime? ExpireOn { get; set; }
}

所以Id属性不可为空并且ExpireOn是。我在基于空对象模式实现域对象时遇到问题,因为我不知道如何实现不可为空的ExpireOn属性。执行此操作的最佳实用方法是什么?

4

2 回答 2

0

您可以在 Tor 中使用 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; }
}
于 2020-04-20T14:18:50.750 回答
0

我想出了这个解决方案:

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; }
}

问题是它是否可以变得更好?

于 2020-04-20T14:11:10.613 回答