切换(true)与coldfusion中的动态案例?

jan*_*jan 6 coldfusion cfml

为了避免嵌套的if语句并提高可读性,我想switch(true){ ... }在Coldfusion中创建一个 语句.我经常在php中使用它,但是当我在Coldfusion中尝试这个时,我在初始化时遇到以下错误:

模板错误

该表达式必须具有常量值.

当switch case在其条件中使用变量时会发生这种情况,例如:

//this example throws the error
switch(true){
    case foo == 1:
        writeOutput('foo is 1');
    break;
}
Run Code Online (Sandbox Code Playgroud)

使用具有常量值的switch(true){...}语句(如错误解释)确实有效:

//this example doesn't throw the error
switch(true){
    case 1 == 1:
        writeOutput('1 is 1');
    break;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让第一个声明在Coldfusion中工作?也许对变量或某些技巧进行评估,或者这对Coldfusion来说是否明确没有?

Ada*_*ron 2

简而言之:不。case 值需要是可以编译为常量值的值。1==1可以,因为它只是truefoo == 1不能,因为foo只能在运行时可用。

基本上你所描述的是一个if/ else if/else构造,所以只需使用其中之一。