2013-04-18 59 views
1

有沒有一種更簡單的方法可以根據C#.NET2中的int值返回一個字符串?基於int的返回字符串

 if (intRelatedItems == 4) 
     { 
      _relatedCategoryWidth = "3"; 
     } 
     else if (intRelatedItems == 3) 
     { 
      _relatedCategoryWidth = "4"; 
     } 
     else if (intRelatedItems == 2) 
     { 
      _relatedCategoryWidth = "6"; 
     } 
     else if (intRelatedItems == 1) 
     { 
      _relatedCategoryWidth = "12"; 
     } 
     else 
     { 
      _relatedCategoryWidth = "0"; 
     } 
+5

['switch'](http://msdn.microsoft.com/zh-cn/library/06tc147t(v = vs.71).aspx)語句。 –

+0

您可以使用switch語句,它不會*更容易*,但看起來更好,並且導致更少的惱人的代碼寫入。 –

+4

使用'字典' – millimoose

回答

7
Dictionary<int, string> dictionary = new Dictionary<int, string> 
{ 
    {4, "3"}, 
    {3, "4"}, 
    {2, "6"}, 
    {1, "12"}, 
}; 

string defaultValue = "0"; 

if(dictionary.ContainsKey(intRelatedItems)) 
    _relatedCategoryWidth = dictionary[intRelatedItems]; 
else 
    _relatedCategoryWidth = defaultValue; 

或使用三元運算符,但我覺得它的可讀性:

_relatedCategoryWidth = dictionary.ContainsKey(intRelatedItems) ? dictionary[intRelatedItems] : defaultValue; 

或使用TryGetValue方法,如CodesInChaos好心建議:

if(!dictionary.TryGetValue(intRelatedItems, out _relatedCategoryWidth)) 
    _relatedCategoryWidth = defaultValue; 
+3

我會使用'TryGetValue'' – CodesInChaos

+1

*「,這使得它有點短」* - 不僅簡短,但避免了字典查找兩次。 – GolfWolf

+0

@ w0lf是的,當然,完全同意,但只有4個字典中的項目,我只喜歡擔心可讀性。 –

1

好吧,既然你只對特殊外殼連續小整數感興趣,你可以用數組查找來做這件事:

var values = new[] { "0", "12", "6", "4", "3" }; 
if (intRelatedItems >= 0 && intRelatedItems < values.Length) 
{ 
    return values[intRelatedItems]; 
} 
else 
{ 
    return "0"; 
} 

否則,最好的辦法是去一個普通的舊switch/case和可能隱藏的方法裏面,這樣它不會弄亂代碼。

0

根據您的密鑰,您可以使用int[]Dictionary<int, string>

例如:

int[] values = new int[] {100, 20, 10, 5}; 
return values[intRelatedItems]; 

顯然,只有當intRelatedItems只能取值從0到values.Length工作-1。

如果不是這種情況,您可以使用'詞典'。如果找不到密鑰,這兩種解決方案都會引發異常。

0
Dictionary<int, string> dictLookUp = new Dictionary<int, string>(); 
dictLookUp.Add(4, "3"); 
dictLookUp.Add(3, "4"}; 
dictLookUp.Add(2, "6"}; 
dictLookUp.Add(1, "12"}; 

int defaultVal = 0; 

if (dictLookUp.ContainsKey(intRelatedItems)) 
{ 
    relatedCategoryWidth = dictLookUp[intRelatedItems]; 
} 
else 
{ 
    intRelatedItems = defaultVal; 
} 
1

可以使用條件運算符:

_relatedCategoryWidth = 
    intRelatedItems == 4 ? "3" : 
    intRelatedItems == 3 ? "4" : 
    intRelatedItems == 2 ? "6" : 
    intRelatedItems == 1 ? "12" : 
    "0"; 

寫它的這種方式強調,一切都歸結爲一個賦值給變量_relatedCategoryWidth