何时在 switch 语句上使用 If-else if-else,反之亦然 [英] When to use If-else if-else over switch statements and vice versa

查看:46
本文介绍了何时在 switch 语句上使用 If-else if-else,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要在一系列 if 语句上使用 switch 块?

Why you would want to use a switch block over a series of if statements?

switch 语句似乎做同样的事情,但输入时间更长.

switch statements seem to do the same thing but take longer to type.

推荐答案

与大多数事情一样,您应该根据上下文选择要使用的内容以及概念上正确的方法.开关实际上是在说根据这个变量值选择其中一个",但 if 语句只是一系列布尔检查.

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

举个例子,如果你在做:

As an example, if you were doing:

int value = // some value
if (value == 1) {
    doThis();
} else if (value == 2) {
    doThat();
} else {
    doTheOther();
}

这将更好地表示为一个开关,因为它可以立即清楚地表明,动作的选择是基于值"的值而不是一些任意测试发生的.

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

此外,如果您发现自己编写开关和 if-else 并使用 OO 语言,您应该考虑摆脱它们并尽可能使用多态来实现相同的结果.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

最后,关于切换需要更长时间打字,我不记得是谁说的,但我曾经读到有人问你的打字速度真的会影响你编码的速度吗?"(转述)

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)

这篇关于何时在 switch 语句上使用 If-else if-else,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆