模型:
public class ServiceHours
{
public int Id { get; set; }
...
public TimeSpan? Monday { get; set; }
public TimeSpan? Tuesday { get; set; }
public TimeSpan? Wednesday { get; set; }
public TimeSpan? Thursday { get; set; }
public TimeSpan? Friday { get; set; }
public TimeSpan? Saturday { get; set; }
public TimeSpan? Sunday { get; set; }
}
我目前正在遍历“服务时间”对象列表(它们可以为一周中的 1 天或多天保留可选的开始时间)。我希望能够动态地从对象中获取对应于DayOfWeek
枚举的值。DateTime
这有效,但不是很优雅
var today = DateTime.Today.DayOfWeek;
foreach (var item in myItems)
{
var time = new TimeSpan?();
if (today == DayOfWeek.Monday)
time = item.Monday;
else if (today == DayOfWeek.Tuesday)
time = item.Tuesday;
else if (today == DayOfWeek.Wednesday)
time = item.Wednesday;
else if (today == DayOfWeek.Thursday)
time = item.Thursday;
else if (today == DayOfWeek.Friday)
time = item.Friday;
else if (today == DayOfWeek.Saturday)
time = item.Saturday;
else if (today == DayOfWeek.Sunday)
time = item.Sunday;
...
}
更新:当时我最终使用了反射,但这是一个非常糟糕、幼稚的设计,无论如何这个问题应该已经发布到代码审查 - 这个问题应该被忽略,只需添加这个通知以防万一一起来。感谢那些不顾可怕问题而试图提供帮助的人!