哈希键和值的比较不相等 [重复]

Hash key and value do not compare equally [duplicate]

提问人:lit 提问时间:9/2/2023 更新时间:9/2/2023 访问量:37

问:

为什么整数哈希键不是整数?键的类型为 KeyCollection,即使它是从常量整数创建的。

生成此输出的脚本如下。我将仅显示最后三 (3) 个命令行。为什么键不是某种类型的整数?

PS C:\> $h.Keys[0].GetType()    # the type of the first and only item in the set of keys is KeyCollection, not an int of some kind

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
False    False    KeyCollection                            System.Object

PS C:\> 1 -eq $h.Keys[0]        # comparing 1 and the key both ways produces different results ???
False
PS C:\> $h.Keys[0] -eq 1
1

PS C:\> $PSVersionTable.PSVersion.ToString()
7.3.6

这是导致这种情况的脚本。

$h = @{}
$hi1 = @{1='a';2='b'}   # create a hash
$h.GetType()            # yes, it is a hashtable
$h.Count                # there should be none (0) at this point
$h[1] += @($hi1)        # put an array containing a hash into h
$h[1]                   # check to see that the array containing a hash is in the hash h
$h[1].Count             # there should be one (1) item in the hash
$h[1].GetType()         # the item at hash index 1 should be an array
$h[1][0]                # this is the first and only element in the array
$h[1][0].GetType()      # the first item in the array is a hashtable

$h.Keys                 # there is only one key in the hash
$h.Keys.GetType()       # the type of the Keys object is a KeyCollection
$h.Keys[0]              # the first and only item in the set of keys is 1
$h.Keys[0].GetType()    # the type of the first and only item in the set of keys is KeyCollection, not an int of some kind
1 -eq $h.Keys[0]        # comparing 1 and the key both ways produces different results ???
$h.Keys[0] -eq 1
PowerShell -核心 PowerShell-7

评论

0赞 Santiago Squarzon 9/2/2023
“为什么整数哈希键不是整数?”你不能索引键集合,你会注意到,如果你在哈希中添加了多个键,它们仍然保留类型。$h = @{ 1 = 1; 2 = 2 }; $h.Keys[0]; $h.Keys | % GetType

答:

4赞 paul_t 9/2/2023 #1

看起来这个问题可能已经在这里得到了回答

如果这没有帮助,

据我了解,该属性返回的 KeyCollection 对象没有索引(也没有内置的迭代器)。因此,当您尝试使用 indice 0 索引到对象时,PowerShell 只是返回整个对象。例如,如果您尝试访问 indice 1,您将一无所获。Keys

您应该能够通过执行类似于 的操作将 Keys 对象转换为数组。然后,您可以根据需要访问此数组上的索引(请注意,键的顺序似乎是向后排列的?我假设在这种情况下键顺序可能是未定义的)[Array]$keys_arr = $h.Keys

或者,如果您只需要访问特定索引,则可以执行以下操作([Array]$h.Keys)[0] -eq ...

除了上面链接的 SO 帖子外,您还可以在这篇 Reddit 帖子中阅读更多关于 KeyCollections 的信息。

至于为什么在翻转等式语句时会得到不同的结果,Jeroen Mostert 对另一个答案的评论似乎很好地解释了 PWSH 中 -eq 的非对称性质:

PowerShell 中的相等性不是对称操作。根据文档:“当输入是值的集合时,比较运算符返回任何匹配的值。如果集合中没有匹配项,则比较运算符不会返回任何内容。因此,$null -eq $abc测试$abc本身是否$null,$abc -eq $null 在 $abc 中找到$null值,并且不打印任何值,因为这是输出时$null的样子。(比较 $abc -eq 7。

希望这有帮助!