【问题标题】:Recursion and return Dates in C#C#中的递归和返回日期
【发布时间】:2009-10-08 02:58:51
【问题描述】:

我无法让此方法返回正确的日期。此方法的作用是获取当前日期并添加您指定的天数。因此,如果您想要下周一,它将在下周一返回。它还将日期发送到一个方法,该方法检查它是否是不允许返回的“过滤日期”之一。除了递归之外,这一切都很好。我想要做的是,如果日期是“过滤日期”,再次运行相同的方法,添加天数直到它到达未过滤的日期。发生的情况是说我在 2009 年 10 月 12 日传递,这是一个过滤的日期,它执行递归,添加天数并返回 10/19/2009 但看起来它再次返回但返回 10/12/2009 .我究竟做错了什么?谢谢

private static DateTime Next(DateTime current, DayOfWeek dayOfWeek, int weeksAhead)
{
    int offsetDays = dayOfWeek - current.DayOfWeek;
    if (offsetDays <= 0)
    {
        offsetDays += 7 * weeksAhead;
    }
    DateTime result = current.AddDays(offsetDays);
    //MAKE SURE RESULT IS NOT A FILTERED DATE
    if (IsFiltered(result))
    {
        Next(result, dayOfWeek, 1);

    }
    //IF IT IS, RUN NEXT AGAIN WITH AN INCREMENTAL WEEK
    return result;
}

【问题讨论】:

    标签: c# datetime recursion


    【解决方案1】:

    替换

    Next(result, dayOfWeek, 1);
    

    return Next(result, dayOfWeek, 1);
    

    您没有返回(也没有存储)递归调用的结果。

    【讨论】:

      【解决方案2】:
      
      private static DateTime Next(DateTime current, DayOfWeek dayOfWeek, int weeksAhead)
      {
          current = current
              .AddDays((current.DayOfWeek - dayOfWeek) * -1)
              .AddDays(7 * weeksAhead);
      
          // recursive approach
          if (IsFiltered(current))
          {
              return Next(current, dayOfWeek, 1);
          }
          else
          {
              return current;
          }
      
          // I prefer this approach, without recursion
          while(IsFiltered(current))
              current = Next(current, dayOfWeek, 1);
          return current;
      }
      

      【讨论】:

        【解决方案3】:

        您没有在 if(IsFiltered(result)) 语句中返回结果。 将其更改为:

        if (IsFiltered(result))
        {
            return Next(result, dayOfWeek, 1);
        }
        else
        {
            return result;
        }
        

        【讨论】:

          猜你喜欢
          • 2013-08-25
          • 2013-12-12
          • 2021-03-14
          • 2014-04-17
          • 2020-04-04
          • 1970-01-01
          • 2014-12-25
          • 2019-09-12
          • 1970-01-01
          相关资源
          最近更新 更多