-1

模型:

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;

    ...
}

更新:当时我最终使用了反射,但这是一个非常糟糕、幼稚的设计,无论如何这个问题应该已经发布到代码审查 - 这个问题应该被忽略,只需添加这个通知以防万一一起来。感谢那些不顾可怕问题而试图提供帮助的人!

4

2 回答 2

1

如果您能够修改object构成objectList变量的类,请尝试Dictionary<DayOfWeek, TimeSpan?>在该类中使用 a。DayOfWeek将是key并且TimeSpan?将是value。这将简化课程并消除冗长的if-else逻辑。

另外,如果我没记错的话,这种方法也比使用反射更快,并且不会依赖于你的属性名称object拼写与一周中的几天完全相同DayOfWeek(如果你需要重构一些将来的原因)。

这是一个例子:

static void Main(string[] args)
{
    List<WeekObject> weekObjs = new List<WeekObject>();

    foreach (var obj in weekObjs)
    {
        SaveTime(obj.ID, obj.weekDictionary[DateTime.Today.DayOfWeek]);
    }
}

class WeekObject
{
    public int ID { get; set; }
    public Dictionary<DayOfWeek, TimeSpan?> weekDictionary { get; set; } = new Dictionary<DayOfWeek, TimeSpan?>();

    public WeekObject ()
    {
        // Initialize dictionary here if you'd like
        weekDictionary.Add(DayOfWeek.Sunday, null);
    }
}

public static void SaveTime(int ID, TimeSpan? timeSpan)
{
    // Your code here
}
于 2018-03-28T20:41:58.120 回答
0

Something like this probably (did not compiled this code though)

object.GetType().GetProperty(today.DayOfWeek.ToSring()).GetValue(object)

use reflection to get property value,with only condition that DayOfWeek enum member has to have exact name of the property present in object type.

于 2018-03-28T20:37:34.887 回答