添加天数到C#Nullable DateTime对象不在While循环中执行

时间:2016-09-15 16:06:00

标签: c# loops datetime for-loop nullable

我在这里编写一些生产代码,并且必须在代码之上添加一些我自己设计的代码,这些代码已经有点问题了。我有一个循环,可以帮助根据某个支付期计算日期。

我遇到的问题是,当使用Nullable DateTime函数调用添加值时,我的DateTime?.Value.AddDays()个对象根本没有变化。当我运行此代码时,nextPayDate对象及其值保持不变,即使我在循环期间添加它。所述行为没有用,并且还创建了无限循环。思考?

public static List<DateTime?> GetLPSPaymentDates(Applicant applicant, int loanTermType, DateTime deliveryConfirmationDate)
{

    if (applicant == null)
    {
        throw new Exception("The applicant you are wanting to set an LPS for is null");
    }

    DateTime? firstPaymentDate = DateTime.Today;
    DateTime? secondPaymentDate = DateTime.Today;
    DateTime? lastPayDate = applicant.MainEmployer.LastPayDate;
    DateTime? nextPayDate = applicant.MainEmployer.NextPayDate;

    DateTime? earliestPossiblePaymentDate =   deliveryConfirmationDate.AddDays(10);

    int daysToAdd = 0;
    if (lastPayDate != null && nextPayDate != null)
    {
        var tempDate = nextPayDate;
        while (tempDate.Value <= earliestPossiblePaymentDate.Value)
        {
            daysToAdd =     IncrementPaymentDateByTermType((TermTypes)loanTermType);
            nextPayDate.Value.AddDays(daysToAdd);
            firstPaymentDate.Value.AddDays(daysToAdd);
        }
        if (firstPaymentDate == DateTime.Today)
        {
            firstPaymentDate = nextPayDate;
        }
        secondPaymentDate = firstPaymentDate.Value.AddDays(daysToAdd); 
    }
    else
    {
        throw new Exception("Could not find applicant's last or next pay date.");
    }

    List<DateTime?> firstAndSecondDates = new List<DateTime?>()
    {
        firstPaymentDate,
        secondPaymentDate
    };

    return firstAndSecondDates;

}

public static int IncrementPaymentDateByTermType(TermTypes termType)
{
    int numberOfDaysToAdd;

    switch (termType)
    {
        case TermTypes.BiWeekly:
            numberOfDaysToAdd = 14; 
            break;
        case TermTypes.Weekly:
            numberOfDaysToAdd = 7;
            break;
        default:
            numberOfDaysToAdd = 1;
            break;
    }
    return numberOfDaysToAdd;
}

2 个答案:

答案 0 :(得分:1)

AddDays返回一个新对象作为结果,而不是更新现有对象。尝试:

daysToAdd = IncrementPaymentDateByTermType((TermTypes)loanTermType);
nextPayDate = nextPayDate.Value.AddDays(daysToAdd);
firstPaymentDate = firstPaymentDate.Value.AddDays(daysToAdd);

答案 1 :(得分:0)

没有测试过,但这应该有所帮助(假设你的while循环逻辑是正确的)

while (tempDate.Value <= earliestPossiblePaymentDate.Value)
{
    daysToAdd = IncrementPaymentDateByTermType((TermTypes)loanTermType);
    tempDate = nextPayDate.Value.AddDays(daysToAdd); // <<= updating tempDate
    firstPaymentDate.Value.AddDays(daysToAdd);
}