有没有更好的方法来比较C#中的这些值?

时间:2013-06-26 21:24:42

标签: c# compare

我有比较这样的值的方法:

protected bool CompareValues(string a="", int b=0, string c="", int d=0, string e="", int f=0)
{
int counter = 0;

if(int.Parse(a) > b)
{
  counter++;
}
if(int.Parse(c) > d)
{
  counter++;
}

if(counter > 1)
{
 counter = 1;
}

 if(int.Parse(e) > f)
{
  counter++;
}

if(counter > 1)
{
  return true;
}
else
{
 return false;
}

}

它适用于我,但如果可能的话,我不能不考虑一些改进。任何建议都会受到赞赏。

4 个答案:

答案 0 :(得分:0)

我不确定你为什么将counter重置为1,但这是我理解的

if((int.Parse(a) > b || int.Parse(c) > d) && int.Parse(e) > f)
{
   return true;
}
else
{
   return false;
}

答案 1 :(得分:0)

看起来你想要:

return (int.Parse(a) > b || int.Parse(c) > d) && int.Parse(e) > f;

答案 2 :(得分:0)

我不确定,但这是你想要做的吗?

return ( ( int.Parse(a) > b || int.Parse(c) > d ) && int.Parse(e) > f);

答案 3 :(得分:0)

如果您需要对表格进行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);
    }

当然,必须选择从重载传递的参数,以使语义合适。

相关问题