作者:-独享你的温情 | 来源:互联网 | 2022-12-09 17:18
有几种语言可以提供默认或逻辑或分配机制:
a = b || c;
a = b or c
a="${b:-$c}"
a = b ? b : c;
到目前为止,我在Powershell Core中找到的唯一等价物是非常冗长:
$a = if ($b) { $b } else { $c }
在某些情况下必须成为
$a = if ($b -ne $null) { $b } else { $c }
有没有更好的选择[编辑:],这不会牺牲可读性?
1> Mathias R. J..:
||
PowerShell赋值中没有短路运算符,也没有与Perl的//
"定义或"运算符等效的东西- 但是你可以构造一个简单的null coalesce模仿,如下所示:
function ?? {
param(
[Parameter(Mandatory=$true,ValueFromRemainingArguments=$true,Position=0)]
[psobject[]]$InputObject,
[switch]$Truthy
)
foreach($object in $InputObject){
if($Truthy -and $object){
return $object
}
elseif($object -ne $null){
return $object
}
}
}
然后使用像:
$a = ?? $b $c
或者,如果你想$true
在第一个例子中返回任何已经评估过的东西:
$a = ?? $b $c -Truthy