C# 有没有办法减少这个switch语句?
我本来打算使用if语句,但我的作业要求我使用switchC# 有没有办法减少这个switch语句?,c#,switch-statement,case,C#,Switch Statement,Case,我本来打算使用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 in
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;
您的代码尽可能简洁。运行时的
switch
语句实际上是一个跳转表,因此它比一系列if()
语句要快得多,即使将if
语句合并到范围表达式中(例如if(1您的代码尽可能简洁。运行时的switch
语句实际上是一个跳转表,因此它比一系列if()
语句要快得多,即使您将if
语句合并到范围表达式中(例如if(1)您也缺少中断。case变量和乘法器之间是否存在数学关系?我看不出来。@OldProgrammer我看不到任何缺少的中断。代码不需要任何中断来执行它试图执行的操作。@Thibaut没有不必要的情况可以忽略。如果您的赋值需要一个开关,则n没有什么比这更好的了。当然,你可以做很多更好的事情,不需要使用开关。你也缺少break。case变量和乘法器之间有数学关系吗?我看不出一个。@old程序员我看不到任何缺少breaks。代码不需要任何中断来完成它试图做的事情。@Thibaut没有不必要的情况可以忽略。如果你的作业需要一个开关,那么你就没有什么可以做得更好的了。当然,你可以做很多更好的事情,而不需要使用开关。
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;
<#
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("}");
#>