C#重构这个凌乱的代码!

时间:2009-08-05 21:00:00

标签: c# refactoring

我基本上为时间表页面(ASP.NET MVC)创建一个平面视图模型,该页面具有一周中几天的网格。 WorkTime属性应该是数据库中的现有WorkTime,如果没有,则为null。

只会显示1周(周六至周五)。我在那里有各自的属性,以便我的视图中的语法应该更简单。

+------+-----+-----+-----+-----+-----+-----+-----+
| Desc | Sat | Sun | Mon | Tue | Wed | Thu | Fri |
+------+-----+-----+-----+-----+-----+-----+-----+
|______|_____|_____|_____|_____|_____|_____|_____|
|______|_____|_____|_____|_____|_____|_____|_____|
|______|_____|_____|_____|_____|_____|_____|_____|
|______|_____|_____|_____|_____|_____|_____|_____|

来自和持久存储到数据库的所有日期都没有Time元素(所有午夜时间),并且星期六到星期五DateTime属性都已设置。

我正在设置的属性

public WorkTime SaturdayWorkTime { get; private set; }
public WorkTime SundayWorkTime { get; private set; }
public WorkTime MondayWorkTime { get; private set; }
public WorkTime TuesdayWorkTime { get; private set; }
public WorkTime WednesdayWorkTime { get; private set; }
public WorkTime ThursdayWorkTime { get; private set; }
public WorkTime FridayWorkTime { get; private set; }

当前迭代......

public DateTime Saturday { get; private set; }
public DateTime Sunday { get; private set; }
public DateTime Monday { get; private set; }
public DateTime Tuesday { get; private set; }
public DateTime Wednesday { get; private set; }
public DateTime Thursday { get; private set; }
public DateTime Friday { get; private set; }

_workTimes = _workTimeRepository.GetByWorkAssignmentID(WorkAssignment.ID, Saturday, Friday);
SaturdayWorkTime = GetWorkTimeForDay(DayOfWeek.Saturday);
SundayWorkTime = GetWorkTimeForDay(DayOfWeek.Sunday);
MondayWorkTime = GetWorkTimeForDay(DayOfWeek.Monday);
TuesdayWorkTime = GetWorkTimeForDay(DayOfWeek.Tuesday);
WednesdayWorkTime = GetWorkTimeForDay(DayOfWeek.Wednesday);
ThursdayWorkTime = GetWorkTimeForDay(DayOfWeek.Thursday);
FridayWorkTime = GetWorkTimeForDay(DayOfWeek.Friday);

使用这个辅助方法...

private WorkTime GetWorkTimeForDay(DayOfWeek dow)
{
    return _workTimes.FirstOrDefault(x => x.Date.DayOfWeek == dow);
}

5 个答案:

答案 0 :(得分:4)

这是一个小小的开始:

private WorkTime GetWorkTimeForDay(DayOfWeek dw)
{
    return workTimes.FirstOrDefault(x => x.Date.DayOfWeek == dw);
}

答案 1 :(得分:4)

为什么不创建一个字典来存储这些工作时间?

private Dictionary<DayOfWeek, WorkTime> _workTimes;

使用_workTimeRepository.GetByWorkAssignmentID填充此字典应该非常简单。

答案 2 :(得分:3)

你可以使用DayOfWeek枚举。

DateTime now = DateTime.Now;
var dayOfWeek = now.DayOfWeek;

link

答案 3 :(得分:0)

您可以拥有从DayOfWeek到WorkTime的地图,以及从DayOfWeek到DateTime的另一个地图,而不是拥有单个变量吗?对不起,我的C#生锈了,所以这可能不太对,但如果你有,那么看起来会更像这样:

for (DayOfWeek day : allDays) 
    workTimes(day) = repository.FirstOrDefault(dateTimes(day));

答案 4 :(得分:0)

为什么不只是拥有一个WorkTime属性,并使其成为一个Dictionary并从您的工作时间存储库中返回字典(而不是您的列表)。