我现在有一个切换声明,看起来很粗糙。它有效,但它非常粗糙和重复,因为我实际上有另一个类似它的开关语句(它采用不同的变量)。
if (time == 15)
{
percent = policyGroup[0];
}
else
{
percent = policyGroup[1];
}
var currentVal = Convert.ToDouble(profit[i]);
switch (CSR[i])
{
case "Buford":
Buford += currentVal * percent;
break;
case "Cain":
Cain += currentVal * percent;
break;
case "Young":
Young += currentVal * percent;
break;
case "Thomas":
Thomas += currentVal * percent;
break;
case "Armendt":
Armendt += currentVal * percent;
break;
case "Vanover":
Vanover += currentVal * percent;
break;
case "Phillips":
Phillips += currentVal * percent;
break;
case "Smalley":
Smalley += currentVal * percent;
break;
case "Pitman":
Pitman += currentVal * percent;
break;
case "Huse":
Huse += currentVal * percent;
break;
case "Nichols":
Nichols += currentVal * percent;
break;
}
答案 0 :(得分:3)
必须看起来非常厚实的部分是所有变量的声明:
double Buford = 0, Cain = 0, Young, Thomas, Armendt, ..., Pitman;
这些变量不应该是硬编码的;相反,您应该使用存储所有每个名称值的关联容器:
IDictionary<string,double> valByName = new Dictionary<string,double> {
{"Buford", 0}
, {"Pitman", 0}
};
现在你可以这样做:
valByName[CSR[i]] = currentVal * percent;