DayOfWeek 获取下一个 DayOfWeek(Monday,Tuesday...Sunday)

DayOfWeek get the next DayOfWeek(Monday,Tuesday...Sunday)

有没有办法将这段代码总结成 1-2 行?

我的目标是return,比如我有一个DayOfWeek是星期一,我想得到之后的那一天(星期二)或者之后的n天。

         switch (_RESETDAY)
        {
            case DayOfWeek.Monday:
                _STARTDAY = DayOfWeek.Tuesday;
                break;
            case DayOfWeek.Tuesday:
                _STARTDAY = DayOfWeek.Wednesday;
                break;
            case DayOfWeek.Wednesday:
                _STARTDAY = DayOfWeek.Thursday;
                break;
            case DayOfWeek.Thursday:
                _STARTDAY = DayOfWeek.Friday;
                break;
            case DayOfWeek.Friday:
                _STARTDAY = DayOfWeek.Saturday;
                break;
            case DayOfWeek.Saturday:
                _STARTDAY = DayOfWeek.Sunday;
                break;
            case DayOfWeek.Sunday:
                _STARTDAY = DayOfWeek.Monday;
                break;
            default:
                _STARTDAY = DayOfWeek.Tuesday;
                break;
        }

是的。

(DayOfWeek)((int)(_RESETDAY+1)%7)

这只是一个 int 枚举,范围从周日 (0) 到周六 (6),根据 MSDN:

The DayOfWeek enumeration represents the day of the week in calendars that have seven days per week. The value of the constants in this enumeration ranges from DayOfWeek.Sunday to DayOfWeek.Saturday. If cast to an integer, its value ranges from zero (which indicates DayOfWeek.Sunday) to six (which indicates DayOfWeek.Saturday).

这么简单的数学就可以做到:

DayOfWeek nextDay = (DayOfWeek)(((int)_RESETDAY + 1) % 7);

如果您需要,请将 + 1 替换为 + n

    static DayOfWeek dayplus (DayOfWeek day)
    {
        if (day == DayOfWeek.Saturday)
            return DayOfWeek.Sunday;
        else
            return day + 1;
    }

例如

Console.WriteLine(dayplus(DayOfWeek.Sunday));

return 星期一

与上面回答的加法和模运算结果相同,但更具可读性恕我直言:

day = (day == DayOfWeek.Saturday) ? DayOfWeek.Sunday : day + 1;

明显的代码意图总是更有趣。

一般情况解决方案使用模运算:

  DayOfWeek _RESETDAY = ...;
  int shift = 1; // can be positive or negative

  // + 7) % 7 to support negative shift´s
  DayOfWeek result = (DayOfWeek) ((((int)_RESETDAY + shift) % 7 + 7) % 7);

可能,最好的实现是隐藏扩展方法中的繁琐公式:

 public static class DayOfWeekExtensions {
   public static DayOfWeekShift(this DayOfWeek value, int shift) {
     return (DayOfWeek) ((((int)value + shift) % 7 + 7) % 7);
   }
 }

 ...

 var result = _RESETDAY.Shift(1);

并略有减少(仅在负偏移不低于 -7 的情况下适用于所有情况):

     return (DayOfWeek)(((int)value + shift + 7) % 7);