当一个空数组的计算结果为False时,为什么一个空的Powershell哈希表的计算结果是True



我正在Powershell 4.0中试用True和False。以下是查看空数组和空哈希表时的结果:

PS C:Userssimon> $a = @()    
PS C:Userssimon> if ($a) { Write-Host "True" } else { Write-Host "False" }
False
PS C:Userssimon> $a = @{}    
PS C:Userssimon> if ($a) { Write-Host "True" } else { Write-Host "False" }
True

当空数组的值为False时,为什么空哈希表的值为True?

根据Powershell文档关于比较运算符:

当输入是值的集合时,比较运算符返回任何匹配的值。如果集合中没有匹配项,比较运算符不返回任何内容。

因此,我希望哈希表和数组在为空时的行为相同,因为它们都是集合。我希望两者的计算结果都为False,因为它们不会向if子句返回任何内容。

这不是真/假的问题。您可以使用布尔运算符$true$false对此进行测试。我使用了$h作为空哈希表@{}

PS C:> $a = @()
PS C:> $h = @{}
PS C:> if ($a -eq $true) { Write-Host "True" } else { Write-Host "False" }
False
if ($h -eq $true)    >  False
if ($a -eq $false)   >  False
if ($h -eq $false)   >  False

也不等于自动变量$null:

if($a -eq $null)     >  False
if($h -eq $null)     >  False

根据iRon的链接,Count是查看哈希表/数组是否为空的更好测试。相关Length

不同的行为将与基本类型有关。

PS C:> $a.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
PS C:> $h.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object

这与if语句的工作方式和Length属性AFAICS有关。以下是我从多篇StackOverflow帖子和外部链接中(公认不可靠)的理解


Get-Member的行为不同-参见Mathias对的解释

$a | Get-Member            # Error - Get-Member : You must specify an object for the Get-Member cmdlet.
$h | Get-Member            # TypeName: System.Collections.Hashtable. Has Count method, no Length property
Get-Member -InputObject $a # TypeName: System.Object[]. Has Count method, has Length property

变量的Length性质不同。但该哈希表没有Length属性——请参阅mjolinar的答案。

$a.Length   > 0
$h.length   > 1

结合Ansgar的链接解释了if语句中的不同行为,因为它似乎隐含地获得了Length属性。它还允许我们这样做:

if ($a.Length -eq $true)    >  False
if ($h.Length -eq $true)    >  True

我认为,与$null相比,使用[String].Net类的IsNullOrEmpty方法会给出不同的输出,因为这也依赖于Length

if ([string]::IsNullOrEmpty($a))    > True
if ([string]::IsNullOrEmpty($h))    > False

最新更新