-3

次のような値を比較する方法があります。

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

4 に答える 4

0

あなたが望むように見えます:

return (int.Parse(a) > b || int.Parse(c) > d) && int.Parse(e) > f;
于 2013-06-26T21:31:03.163 に答える
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);
    }

もちろん、オーバーロードから渡される引数は、セマンティクスが適切になるように選択する必要があります。

于 2013-06-26T22:02:59.790 に答える
0

なぜカウンターを1にリセットしたのか途中でわかりませんが、これは私が理解したものです

if((int.Parse(a) > b || int.Parse(c) > d) && int.Parse(e) > f)
{
   return true;
}
else
{
   return false;
}
于 2013-06-26T21:30:04.593 に答える