VB.NET - 退出函数在退出函数后再次运行

时间:2014-05-22 15:37:58

标签: vb.net recursion

我有一个函数可以从给定日期开始提前N天返回日期。如果返回的日期属于周末或假日,则应将其移至下一个工作日。

Function NDaysAhead(ByVal dtStartDate As DateTime, ByVal nDays As Integer, ByVal isSatWorkDay As Boolean) As DateTime
    Dim dt As DateTime
    dt = dtStartDate.AddDays(nDays)
    If (Weekday(dt) = 7) And Not isSatWorkDay Then
        dt = dt.AddDays(2)
    ElseIf (Weekday(dt) = 1) Then
        dt = dt.AddDays(1)
    End If
    If IsHoliday(dt) Then
        NDaysAhead(dt, 1, isSatWorkDay)
    End If
    Return dt
    Exit Function
End Function

出于某种原因,在它返回日期并到达End Function后,它会返回NDaysAhead(dt, 1, isSatWorkDay),其值为dt(甚至不检查If IsHoliday(dt)条件) 。

我很确定还有其他方法可以获得我需要的东西,但我真的很想知道为什么会这样做。

由于

1 个答案:

答案 0 :(得分:3)

调用递归方法时,您没有设置dt变量:

NDaysAhead(dt, 1, isSatWorkDay)

应该是

dt = NDaysAhead(dt, 1, isSatWorkDay)

但我认为你应该像这样简化代码,因为实际上不需要递归:

Function NDaysAhead(ByVal dtStartDate As DateTime, ByVal nDays As Integer, ByVal isSatWorkDay As Boolean) As DateTime
    Dim dt As DateTime
    dt = dtStartDate.AddDays(nDays)
    Do Until (Not dt.DayOfWeek = DayOfWeek.Saturday) AndAlso 
             (Not dt.DayOfWeek = DayOfWeek.Sunday) AndAlso 
             (Not IsHoliday(dt))
        dt = dt.AddDays(1)
    Loop
    Return dt
End Function