不中断的 switch 语句 [英] switch statement without break
问题描述
为什么 switch 语句中的 case 选项不包含 break 会自动转发到下一个 case 而不检查?
How come a case option in a switch statement that does not contain a break automatically forwards to a next case without check?
try {
switch($param) {
case "created":
if(!($value instanceof \DateTime))
throw new \Exception("\DateTime expected, ".gettype($value)." given for self::$param");
case "Creator":
if(!($value instanceof \Base\User)) {
throw new \Exception(get_class($value)." given. \Base\User expected for self::\$Creator");
}
default:
$this->$param = $value;
break;
}
} catch(Exception $e) {
echo $e->getMessage();
}
如果参数是创建的",它将在创建的情况下进行检查,这很好.当检查成功时,我希望代码继续使用默认选项,这就是为什么没有中断;.但是它继续Creator",而 $param != "Creator"!
If the param is "created" it will do the check in the created-case, which is good. When the check is succesful, I want the code to continue to the default option, that's why there is no break;. But instead it continues to "Creator" while $param != "Creator"!
我确实知道如何解决这个问题(只需在我的创建"案例中添加默认代码),但我不喜欢过于频繁地重复该代码.我的实际问题是:为什么它继续使用Creator"案例,而案例不是Creator".
I do know how to solve this (just add the default code in my case "created"), but I don't like to repeat that code too often. My actual question is: Why does it continue with the "Creator" case while the case is not "Creator".
推荐答案
Fallthrough 是一个有意设计的特性,用于允许如下代码:
Fallthrough was an intentional design feature for allowing code like:
switch ($command) {
case "exit":
case "quit":
quit();
break;
case "reset":
stop();
case "start":
start();
break;
}
它的设计使执行逐个进行.
It's designed so that execution runs down from case to case.
default
与任何其他情况一样,只是如果没有触发其他情况,则会跳转到那里.它绝不是在运行实际选定的案例后执行此操作"指令.在您的示例中,您可以考虑:
default
is a case like any other, except that jumping there happens if no other case was triggered. It is not by any means a "do this after running the actual selected case" instruction. In your example, you could consider:
switch($param) {
case "created":
if(!($value instanceof \DateTime))
throw new \Exception("\DateTime expected, ".gettype($value)." given for self::$param");
break;
case "Creator":
if(!($value instanceof \Base\User)) {
throw new \Exception(get_class($value)." given. \Base\User expected for self::\$Creator");
}
break;
}
$this->$param = $value;
这里的经验法则是,如果它不依赖于开关,请将其移出开关.
The rule of thumb here is, if it doesn't depend on the switch, move it out of the switch.
这篇关于不中断的 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!