我有一个DateTime变量,可以为null或Datetime。我认为可以为空的DateTime类型可以工作,但是我收到一条错误消息,说



。有什么办法可以解决此错误?

DateTime? lastInvite = (DateTime?)Session["LastInviteSent"];

if ((string)Session["InviteNudgeFlag"] == "False" && ((lastInvite == null && DateTime.Now >= AcctCreation.AddDays(7)) || (int)Session["InviteCount"] > 0 && DateTime.Now >= lastInvite.AddDays(7)))
{
   // Non important code here
}

最佳答案

您应该考虑尝试使逻辑更具可读性:

var inviteNudgeFlag = bool.Parse((string) Session["InviteNudgeFlag"]);

if(!inviteNudgeFlag)
{
    return;
}

var lastInvite = (DateTime?) Session["LastInviteSent"];
var inviteCount = (int) Session["InviteCount"];
var numOfDays = 7;
var now = DateTime.Now;

var weekSinceLastInvite = lastInvite.HasValue
                            ? now >= lastInvite.Value.AddDays(numOfDays)
                            : now >= AcctCreation.AddDays(numOfDays);

var hasInvites = !lastInvite.HasValue || inviteCount > 0;
var canInvite = hasInvites && weekSinceLastInvite;

if(!canInvite)
{
    return;
}

关于c# - 可空的DateTimes和AddDays()扩展,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18518931/

10-09 09:29