有没有办法将这段代码汇总成1-2行?
我的目标是返回,例如,我有一个星期一的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;
}
答案 0 :(得分:10)
这只是一个int枚举,从星期日(0)到星期六(6),根据MSDN:
DayOfWeek枚举表示每周七天的日历中的星期几。此枚举中常量的值范围从DayOfWeek.Sunday到DayOfWeek.Saturday。如果强制转换为整数,则其值的范围为零(表示DayOfWeek.Sunday)至六(表示DayOfWeek.Saturday)。
如此简单的数学应该这样做:
DayOfWeek nextDay = (DayOfWeek)(((int)_RESETDAY + 1) % 7);
如果您需要,请将+ 1
替换为+ n
。
答案 1 :(得分:4)
是
(DayOfWeek)((int)(_RESETDAY+1)%7)
答案 2 :(得分:2)
与上面回答的加法和模数相同的结果,但更可读的imho:
day = (day == DayOfWeek.Saturday) ? DayOfWeek.Sunday : day + 1;
明显的代码意图总是更有趣。
答案 3 :(得分:0)
static DayOfWeek dayplus (DayOfWeek day)
{
if (day == DayOfWeek.Saturday)
return DayOfWeek.Sunday;
else
return day + 1;
}
例如
Console.WriteLine(dayplus(DayOfWeek.Sunday));
将返回星期一
答案 4 :(得分:0)
一般情况解决方案使用模数arithemtics :
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);
可能,最好的方法是隐藏 扩展方法中的combersome公式:
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);