2013-06-26 56 views
-3

我有這樣的比較值的方法:有沒有更好的方法來比較C#中的這些值?

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; 
} 

} 

它工作正常的我,但我不能忍受沒有想着如果可能有所改善。任何建議,將不勝感激。

+1

你想達到什麼目的? –

+0

你爲什麼要增加'計數器'只能將它設回一個? – Eonasdan

+0

我認爲這很明顯。我正在比較值並根據結果返回true或false。這是我最近的項目 –

回答

0

如果您需要執行的形式

(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); 
    } 

當然,從過載傳下來的參數必須是選擇這樣的語義是適當的。

+0

這是我正在尋找的最佳答案。我不想用我在我的問題中編寫的方式指定所有參數,因爲如果參數的數量隨時間增加,它會看起來很醜 –

0

我不知道在中間你爲什麼計數器重置爲1,但是這是我的理解

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

這是正確的。我感興趣的是有沒有其他方式可以通過其他形式傳遞參數? –

+0

我不確定你的意思是其他形式。你的意思是其他類型,如對象或var? –

+0

通過其他形式,我的意思是更短的方式 –

0

它看起來像你想:

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

我不知道,但這是你正在嘗試做什麼?

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

是的。我沒有問題,我只是感興趣的是有沒有比我的例子更好的傳遞參數的方法。 –

+0

你的意思是說更好? –

+0

我的意思是如果我必須比較6個以上的值,會發生什麼。 –

相關問題