if ((ddl1.SelectedValue == "1") || (ddl1.SelectedValue == "100"))
{
if (Fee > 0)
{
Messages += " [Please the check fee and ddl1 type selected] ";
}
}
else if ((ddl1.SelectedValue == "2") || (ddl1.SelectedValue == "200"))
{
if (Fee == 0)
{
Messages += " [Please the check fee and ddl1 type selected] ";
}
}
//如何以最简洁的方式重写相同的逻辑?
答案 0 :(得分:4)
if (((ddl1.SelectedValue == "1" || ddl1.SelectedValue == "100") && Fee > 0) ||
((ddl1.SelectedValue == "2" || ddl1.SelectedValue == "200") && Fee == 0 ))
{
Messages += " [Please the check fee and ddl1 type selected] ";
}
最里面的括号是可选的,用于向读者说明而不是编译。
如果您完全确定SelectedValue
永远不会是1,100,2或200以外的其他任何内容,则可以进一步将(ddl1.SelectedValue == "1" || ddl1.SelectedValue == "100")
合并到ddl1.SelectedValue.StartsWith("1")
。如果选定的值包含其他值,或者总域可能会发生变化,则StartsWith将变得脆弱。
答案 1 :(得分:0)
string[] ValidValues = {"1", "100", "2", "200"};
if(Fee >= 0){
Messages += Array.IndexOf(ValidValues, ddl1.SelectedValue) == -1 ? "" : " [Please the check fee and ddl1 type selected] ";
}