如果您需要对表格进行 n 次比较
(int.Parse(a1) > b1 || int.Parse(a2) > b2 || ... || int.Parse(aK) > bK) && int.Parse(aN) > bN
您可以制作一个只接受一组值对进行比较的方法
protected bool CompareValues(params Tuple<string, int>[] comparisons)
{
if(ReferenceEquals(comparisons, null))
{
throw new ArgumentNullException("comparisons");
}
if(comparisons.Length < 1)
{
throw new ArgumentException("At least one pair to compare must be specified");
}
var atLeastOneComparisonSucceeded = comparisons.Length == 1;
for(var i = 0; !atLeastOneComparisonSucceeded && i < comparisons.Length - 1; ++i)
{
atLeastOneComparisonSucceeded = int.Parse(comparisons[i].Item1) > comparisons[i].Item2;
}
var lastIndex = comparisons.Length - 1;
return atLeastOneComparisonSucceeded && int.Parse(comparisons[lastIndex].Item1) > comparisons[lastIndex].Item2;
}
用法:
var result = CompareValues(new Tuple<string, int>("5", 2),
new Tuple<string, int>("3", 1),
new Tuple<string, int>("1", 2));
如果您只需要 3 对值(如原始帖子中所示),则可以为提供适当默认值的方法提供重载,如下所示
protected static bool CompareValues(string a, int b)
{
return CompareValues(a, b, "1", 0);
}
protected static bool CompareValues(string a, int b, string c, int d)
{
return CompareValues(a, b, c, d, "1", 0);
}
protected static bool CompareValues(string a, int b, string c, int d, string e, int f)
{
return ((int.Parse(a) > b || int.Parse(c) > d) && int.Parse(e) > f);
}
当然,必须选择从重载传递下来的参数,以便语义合适。