为什么 PowerShell 比较运算符不枚举大小为 1 的集合? [英] Why do PowerShell comparison operators not enumerate collections of size 1?

查看:30
本文介绍了为什么 PowerShell 比较运算符不枚举大小为 1 的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在检查变量和变量集合是否为空时,比较运算符似乎枚举大小为 2 或更大的集合:

When checking variables and collections of variables for nullity, comparison operators seem to enumerate collections of size 2 or more:

> if ( @( $null, $null ) -eq $null ) { $True } else { $False }
True

但它们不适用于大小为 1 的集合:

But they do not for collections of size 1:

> if ( @( $null ) -eq $null ) { $True } else { $False }
False

我知道使用左侧 ($null -eq @( $null)) 进行空值比较是最佳做法,但有人可以解释这里发生了什么吗?我怀疑有一些更微妙的事情会影响我编写的其他代码.

I'm aware that it's best practice to null-compare using the left-hand side ($null -eq @( $null )), but can someone explain what's happening here? I suspect there's something more subtle happening that impacts other code that I write.

为什么这两个结果不同?

Why are these two results different?

推荐答案

以下项目评估为 $false:

@()
0
$null
$false
''

<小时>

在你的第一个例子中:


In your first example:

@($null, $null) -eq $null

计算结果为 $null, $null,这是一个非零集合,所以它是 $true.您可以通过以下方式观察这一点:

This evaluates to $null, $null which is a non-zero collection, so it is $true. You can observe this with the following:

[bool]($null, $null)

<小时>

在您的第二个示例中,您观察到的是像第一种情况一样过滤数组,但是 返回标量(而不是数组),因为 数组中只有一项与过滤器匹配:


In your second example, what you're observing is filtering of an array like the first case, but returning a scalar (instead of an array) since only one item of the array matched the filter:

@($null) -eq $null

计算结果为 @($null) 但 powershell 将其计算为布尔上下文中的标量,因此它返回 $false,观察者:

This evaluates to @($null) but powershell is evaluating it as a scalar in a boolean context, so it returns $false, observed by:

[bool]@($null)

<小时>

脚注:在 powershell v2 中,$null 过滤存在一个错误,它产生了左侧的 $null 比较.这个错误导致 if/else 块被完全跳过.


Footnote: in powershell v2, there was a bug with $null filtering which spawned the left-hand $null comparison. This bug caused if/else blocks to be skipped entirely.

这篇关于为什么 PowerShell 比较运算符不枚举大小为 1 的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆