【问题标题】:Null Conditional in Powershell?Powershell中的空条件?
【发布时间】:2019-10-25 14:47:44
【问题描述】:

C# 和其他语言通常有空条件 ?.

A?.B?.Do($C);

当 A 或 B 为空时不会出错。 如何在 powershell 中实现类似的东西,有什么更好的方法:

if ($A) {
  if ($B) {
    $A.B.Do($C);
  }
}

【问题讨论】:

    标签: powershell null-conditional-operator


    【解决方案1】:

    Powershell 7 Preview 5 具有处理空值的运算符。 https://devblogs.microsoft.com/powershell/powershell-7-preview-5/

    $a = $null
    
    $a ?? 'is null' # return $a or string if null
    is null
    
    $a ??= 'no longer null'  # assign if null
    
    $a ?? 'is null'
    no longer null
    

    编辑:Powershell 7 Preview 6 增加了更多新运算符:https://devblogs.microsoft.com/powershell/powershell-7-preview-6/。因为变量名可以有一个“?”在名称中,您必须用花括号将变量名称括起来:

    ${A}?.${B}?.Do($C)
    

    【讨论】:

    • .??? 不一样
    • 确实:虽然与 null-conditional [member-access] operator 有关,但您提到的功能是 null-coalescingnull[-conditional] assignment.
    【解决方案2】:

    PowerShell 没有空条件运算符,但它会默默地忽略空值表达式上的 property 引用,因此您可以“跳过”到链末尾的方法调用:

    if($null -ne $A.B){
      $A.B.Do($C)
    }
    

    在任何深度工作:

    if($null -ne ($target = $A.B.C.D.E)){
        $target.Do($C)
    }
    

    【讨论】:

      【解决方案3】:

      正如Mathias R. Jessen's answer 指出的那样,PowerShell 默认属性访问方面具有空条件访问行为(null-soaking) [1];例如,$noSuchVar.Prop 悄悄返回 $null

      js2010's answer 显示相关的 null-coalescing 运算符 (??) / null-conditional-assignment 运算符 (??=) 在 PowerShell [Core] v 7.1+ 中可用

      但是,直到 PowerShell 7.0

      • no 方法可以空条件地忽略 方法 调用$noSuchVar.Foo() 总是失败。

      • 同样,有 no 方法可以空条件地忽略(数组)索引$noSuchVar[0] 总是失败。

      • 如果您选择使用 Set-StrictMode 进行更严格的行为,那么即使是属性访问 null-soaking 也不再是一种选择:使用 Set-StrictMode -Version 1 或更高版本时,$noSuchVar.Prop 会导致错误。

      PowerShell [Core] 7.1+ 中,null-conditional (null-soaking) 运算符 可用

      新的运营商:

      • 具有与 C# 中相同的形式原则上?.?[...]

      • 但是 - 从 v7.1 开始 - 需要 将变量名包含在 {...}

      也就是说,你目前不能只使用$noSuchVar?.Foo()$A?.B$A?[1],你必须使用
      ${noSuchVar}?.Foo()${A}?.B${A}?[1]

      这种繁琐语法的原因是存在向后兼容性问题,因为? 是变量名中的合法字符,因此假设的现有代码(例如$var? = @{ one = 1}; $var?.one)可能会在不使用的情况下中断{...} 消除变量名的歧义;实际上,这样的用法是vanishingly rare

      如果您认为不妨碍新语法比可能破坏具有以? 结尾的变量名的脚本更重要,请通过this GitHub issue 发出您的声音


      [1] PowerShell 的默认行为甚至提供 existence 条件属性访问;例如,$someObject.NoSuchProp 悄悄返回 $null

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-31
        • 2018-07-20
        • 1970-01-01
        相关资源
        最近更新 更多