我有這些if-else語句,我不能重構。我用它們在服務器端使用asp.net進行驗證。如何減少這個枚舉列表的代碼
是否有人請建議方法來減少這些陳述?在這裏,驗證字段和驗證類型是enum
列表。
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationFields.FO.ToString(), ValidationTypes.P.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationFields.FW.ToString(), ValidationTypes.P.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationFields.UF.ToString(), ValidationTypes.P.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.O.ToString(), ValidationTypes.P.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.W.ToString(), ValidationTypes.P.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.P.ToString(), ValidationTypes.C.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.C.ToString(), ValidationTypes.U.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
這是Checknextitem
方法:
public static bool CheckNextItem(string Compareitem1, string comnpareitem2, string items1, string items2)
{
var listContains = Compareitem1 == items1 && comnpareitem2 != items2;
return listContains;
}
,如果我使用此代碼
var invalidComparisons = new ValidationTypes[][] {
new[] { ValidationFields.FO, ValidationTypes.P },
new[] { ValidationFields.FW, ValidationTypes.P },
new[] { ValidationFields.UF, ValidationTypes.O },
new[] { ValidationTypes.O, ValidationTypes.P },
new[] { ValidationTypes.W, ValidationTypes.P },
new[] { ValidationTypes.P, ValidationTypes.C },
new[] { ValidationTypes.C, ValidationTypes.U },
};
我收到編譯時錯誤:「找到implicitly-沒有最好類型類型數組「。
使用一個陣列和一個循環。 – SLaks