您的代碼是簡潔的,因爲它可以。運行時語句switch
實際上是一個跳轉表,因此即使您將if
語句合併到範圍表達式中(例如if(1 <= x && x <= 5)
),它也會比一系列if()
語句快得多。 A switch
的一組case
陳述必須是完整如果你想覆蓋每一個案例(這就是爲什麼你不能使用switch
與非整數值(注意switch
與String
值是一種特殊情況)。
我不能看到案例和被乘數之間的明顯數學關係,它可以用來大大簡化它,但是您可以重構代碼以便在概念上更容易理解 - 我首先刪除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文件。
來源
2017-02-16 22:01:33
Dai
您還缺少休息 – OldProgrammer
案例變量和乘數之間是否存在數學關係?我無法辨別出一個。 –
爲什麼你使用不必要的情況?只留下他們 – Thibaut