2017-02-16 81 views
0

我打算使用if語句,但是我的任務需要我使用開關。有沒有辦法減少這個switch語句?

case 1: 
case 2: 
case 3: 
case 4: 
case 5: return income = hours * 5; 

case 6: 
case 7: return income = hours * 6; 

case 8: 
case 9: 
case 10: return income = hours * 7; ; 

case 11: 
case 12: 
case 13: 
case 14: 
case 15: return income = hours * 7; ; 

case 16: 
case 17: 
case 18: 
case 19: 
case 20: 
case 21: 
case 22: 
case 23: 
case 24: return income = hours * 10; 

default: return 0; 
+2

您還缺少休息 – OldProgrammer

+1

案例變量和乘數之間是否存在數學關係?我無法辨別出一個。 –

+0

爲什麼你使用不必要的情況?只留下他們 – Thibaut

回答

1

您的代碼是簡潔的,因爲它可以。運行時語句switch實際上是一個跳轉表,因此即使您將if語句合併到範圍表達式中(例如if(1 <= x && x <= 5)),它也會比一系列if()語句快得多。 A switch的一組case陳述必須是完整如果你想覆蓋每一個案例(這就是爲什麼你不能使用switch與非整數值(注意switchString值是一種特殊情況)。

我不能看到案例和被乘數之間的明顯數學關係,它可以用來大大簡化它,但是您可以重構代碼以便在概念上更容易理解 - 我首先刪除income = hours *部分並將其移至單獨返回小時費率的獨立功能:

int GetHourlyRate(int hours) { 
    switch(hours) { 
     case 1: case 2: case 3: case 4: case 5: 
      return 5; 
     case 6: case 7: 
      return 6; 
     case 8: case 9: case 10: 
      return 7; 
     case 11: case 12: case 13: case 14: case 15: 
      return 8; // you put 7 in your original example, is that correct and not a typo? 
     default: 
      if(hours <= 24) return 10; 
      return 0; // or throw an exception? 
    } 
} 

int hourlyRate = GetHourlyRate(hours); 
return income = hours * hourlyRate; 

即使您按照我在垂直空間上保存的樣式(因爲C#對空白不敏感)摺疊,塊仍然不可讀,塊仍然不可讀。

一個選項簡化它,至少在視覺上,是用T4到元程序,這會使得維護更加簡單太:

<# 
    using R = Tuple<Int32,Int32>; 

    R[] hourlyRates = new R[] { 
     new R(5, 5), 
     new R(7, 6), 
     new R(10, 7), 
     new R(15, 8), 
     new R(24, 10) 
    }; 

    WriteLine("switch(hours) {"); 

    for(Int32 r = 0, i = 1; r < hourlyRates.Length; i++) { 

     WriteLine("case {0}:", i); 
     if(i == hourlyRates[r].Item1) { 
      WriteLine("return {0};", hourlyRates[r].Item2); 
      r++; 
      if(r >) 
     } 
    } 

    WriteLine("}"); 
#> 

...這將基於在規定的hourlyRates名單上的switch T4文件。

0

您的任務可能需要使用switch語句,但我想您也可以自由使用其他語句。

var values = new[] { 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; 

int value; 
if (hours > 0 && hours < 25) 
    value = values[hours]; 
else 
    value = 0; 

switch (value) 
{ 
    case 1: return hours * 5; 
    case 2: return hours * 6; 
    case 3: return hours * 7; 
    case 4: return hours * 10; 
    default: return 0; 
}