我必须获取一段数据,并将大量可能的变量应用于它.我真的不喜欢使用巨大的if语句集的想法,所以我在寻求简化方法的帮助,并使其更容易维护.
举个例子:
if (isSoccer) val = soccerBaseVal; else if (isFootball) val = footballBaseVal; .... // 20 different sports if (isMale) val += 1; else val += 5; switch(dayOfWeek) { case DayOfWeek.Monday: val += 12; ... }
等等..等等.可能在100-200种不同的测试和配方变化范围内.
这似乎是一场维护噩梦.有什么建议?
编辑:
为了进一步增加问题,许多变量仅在某些情况下使用,因此它不仅仅是具有不同值的固定逻辑集.逻辑本身必须基于条件而改变,可能是从先前变量应用的条件(例如,如果val>阈值).
所以是的,我同意对许多值使用查找,但我也必须有可变逻辑.
解决方法@H_404_18@
避免大型交换结构的常用方法是将信息放入数据结构中.创建枚举SportType和Dictionary< SportType,Int32>包含相关值.你可以简单地写val = sportTypescoreMap [sportType],你就完成了.
这种模式的变化将在许多类似的情况下帮助您.
public enum SportType
{
Soccer,Football,...
}
public sealed class Foo
{
private static readonly IDictionary<SportType,Int32> sportTypescoreMap =
new Dictionary<SportType,Int32>
{
{ Soccer,30 },{ Football,20 },...
}
private static readonly IDictionary<DayOfWeek,Int32> dayOfWeekscoreMap =
new Dictionary<DayOfWeek,Int32>
{
{ DayOfWeek.Monday,12 },{ DayOfWeek.Tuesday,...
}
public Int32 Getscore(SportType sportType,DayOfWeek dayOfWeek)
{
return Foo.sportTypescoreMap[sportType]
+ Foo.dayOfWeekscoreMap[dayOfWeek];
}
}
这种模式的变化将在许多类似的情况下帮助您.
public enum SportType { Soccer,Football,... } public sealed class Foo { private static readonly IDictionary<SportType,Int32> sportTypescoreMap = new Dictionary<SportType,Int32> { { Soccer,30 },{ Football,20 },... } private static readonly IDictionary<DayOfWeek,Int32> dayOfWeekscoreMap = new Dictionary<DayOfWeek,Int32> { { DayOfWeek.Monday,12 },{ DayOfWeek.Tuesday,... } public Int32 Getscore(SportType sportType,DayOfWeek dayOfWeek) { return Foo.sportTypescoreMap[sportType] + Foo.dayOfWeekscoreMap[dayOfWeek]; } }