我在不同的资料中读到,SWITCH语句比多个IF语句产生更好的性能。我有以下具有并行条件的IF语句块。是否可以在SWITCH块中执行此操作?
if (($statusCode -eq "OK:") -and ($messageOutput)) {
$returnValue = 0
return $returnValue
}
if (($statusCode -eq "WARNING:") -and ($messageOutput)) {
$returnValue = 1
return $returnValue
}
提前致谢,
答案 0 :(得分:1)
这里有一个$messageOutput
的常数,因此条件并非真正平行。你可以这样做:
if($messageOutput) {
switch ($statusCode) {
"OK:" { 0 }
"WARNING:" { 1 }
default { 1 }
}
}
由于您不需要为每个条件重新检查每个变量,因此效率会更高。
答案 1 :(得分:0)
对于这种特殊情况,Arco444具有最佳答案。但值得注意的是,switch
块中可能存在多个条件。如果另一个SO用户在这里找到他们的路:
Switch($true){
(($statusCode -eq "OK:") -and ($messageOutput)){"Alright"}
(($statusCode -eq "WARNING:") -and ($messageOutput)){"Not Alright"}
default{"Something Wrong"}
}
条件都是根据$true
是否进行了评估。如果其他条件都不成立,default
将会捕获。
答案 2 :(得分:0)
这是使用Switch处理多个条件的一种方法:
Switch ([string][int[]]($Condition1,$Condition2))
{
'1 1' { 'Both conditions are true' }
'1 0' { 'Condition1 is true and Condition2 is false' }
'0 1' { 'Condition1 is false and Condition2 is true' }
'0 0' { 'Both conditions are false' }
}