【发布时间】:2019-01-01 15:26:36
【问题描述】:
有几种语言提供默认或逻辑或分配机制:
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 }
有没有更好的替代方案 [edit:] 不会牺牲可读性?
【问题讨论】:
-
Here's a good article with an example function。它将
=转换为支持三元和空值合并的函数。 -
有一个feature request on GitHub 可以将此添加到PowerShell语言中;请在那里发出你的声音。
-
@TheIncorrigible1: 是的:有一个related feature request to add ternary conditionals(
Where-Object是在argument模式下解析的,所以和expression模式没有冲突) . -
@kfsone:好问题;顺便说一句:为了可靠地测试
$null,$null必须用作 LHS -$null -ne $b- 因为 RHS 操作数充当 过滤器在 PowerShell 中使用 数组值 LHS(尝试'foo', 'bar' -ne $null)。 -
@mklement0 哦,直到!有更多的理由有一个特定的运营商。
标签: powershell ternary-operator null-coalescing-operator powershell-core