为了避免嵌套的if语句并提高可读性,我想创建一个
Coldfusion中的switch(true){ ... }
声明。我经常在php中使用它,但是当我在Coldfusion中尝试这个时,我在初始化时遇到以下错误:
模板错误
此表达式必须具有常量值。
当switch case在其条件中使用变量时会发生这种情况,例如:
//this example throws the error
switch(true){
case foo == 1:
writeOutput('foo is 1');
break;
}
使用具有常量值的switch(true){...}语句(如错误所解释的)确实有效:
//this example doesn't throw the error
switch(true){
case 1 == 1:
writeOutput('1 is 1');
break;
}
有没有办法让第一个声明在Coldfusion中工作?也许对变量或某些技巧进行评估,或者这在Coldfusion中是否明确没有?
答案 0 :(得分:2)
简而言之:不。案例值必须是编译到常量值的东西。 1==1
可以,因为它只是true
。 foo == 1
不能,因为foo
仅在运行时可用。
基本上你所描述的是一个if
/ else if
/ else
构造,所以只需使用其中一个。
答案 1 :(得分:2)
正如Adam和Leigh指出的那样,案例值需要保持不变。我不确定您的实际用例是什么,但您可以这样做:
switch(foo){
case 1:
writeOutput('foo is 1');
break;
case 2:
writeOutput('foo is 2');
break;
case 3:
writeOutput('foo is 3');
break;
case 4:
case 5:
case 6:
writeOutput('foo is 4 or 5 or 6');
break;
default:
writeOutput("I do not have a case to handle this value: #foo#");
}
答案 2 :(得分:0)
作为对此问题的更新,我将注意到CF2020(当前处于公开Beta版)增加了对动态案例值的支持。
是的,这样做是出于理解,出于性能原因,某些语言不允许这样做。与其他语言一样,他们出于可读性/灵活性的原因选择允许这样做,而让开发人员负责对用例进行成本/收益权衡分析。