如何将价格校验的if else语句转换为switch case语句?
把价格校验的if/else转换成switch/case的实现方案
嘿,我懂你想把这段价格校验的if/else改成switch/case的需求!不过得先说明:常规的switch/case是用来匹配固定值的,但你的逻辑都是基于范围和比较条件的,所以我们得用个小技巧来实现——把switch的判断目标设为true,这样每个case就可以直接写你的条件啦。
先把你的原代码整理清楚(补全了未写完的部分作为示例):
if(sellingPrice <= costPrice) { Response.Write("<script>alert('The value of the selling price must be higher than the cost price!','_self')</script>"); } else if(sellingPrice == 0) { Response.Write("<script>alert('The value of the selling price must not be equal to zero!','_self')</script>"); } else if(costPrice == 0) { Response.Write("<script>alert('Cost price cannot be zero!','_self')</script>"); }
转换后的switch/case代码(C#环境,适配你的Response.Write场景)
switch (true) { case bool when sellingPrice <= costPrice: Response.Write("<script>alert('The value of the selling price must be higher than the cost price!','_self')</script>"); break; case bool when sellingPrice == 0: Response.Write("<script>alert('The value of the selling price must not be equal to zero!','_self')</script>"); break; case bool when costPrice == 0: Response.Write("<script>alert('Cost price cannot be zero!','_self')</script>"); break; default: // 所有条件都不满足时的逻辑,比如什么都不做或者执行正常流程 break; }
关键说明
- 核心技巧:把switch的表达式设为
true,这样每个case的条件只要返回true,就会触发对应的代码块,完美适配你的比较逻辑。 - 跨环境写法:如果是JavaScript环境(比如前端脚本),写法会更简洁:
switch (true) { case sellingPrice <= costPrice: alert('The value of the selling price must be higher than the cost price!'); break; case sellingPrice === 0: alert('The value of the selling price must not be equal to zero!'); break; case costPrice === 0: alert('Cost price cannot be zero!'); break; default: break; }
- 顺序不能乱:switch是从上到下匹配第一个满足条件的case,一定要保持和原if/else一致的判断顺序,否则会出现逻辑偏差(比如如果先判断
sellingPrice ==0,当售价为0且小于成本价时,会触发错误的提示)。 - 可读性建议:如果你的条件不多,这种转换没问题,但如果后续要加更多范围判断,其实原if/else的可读性反而更好——switch更适合固定值匹配的场景哦。
内容的提问来源于stack exchange,提问作者doria_aries
相关产品推荐
相关产品推荐

