我的要求是使用 ordered 中的整数键存储整数键并访问哈希表值。哈希表。
什么有效
当我使用字符串键时,没问题:
cls
$foo=[ordered]@{}
$foo.add("12",1)
$foo.add("24",2)
write-host ("first item=" + $foo.Item("12"))
write-host ("second item=" + $foo.Item("24"))
输出:
first item=1
second item=2
使用括号失败
当我使用括号时,程序不会抛出异常,但它什么都不返回:
$fooInt=[ordered]@{}
$fooInt.add(12,1)
$fooInt.add(24,2)
write-host ("first item=" + $fooInt[12])
write-host ("second item=" + $fooInt[24])
输出:
first item=
second item=
使用 Item 方法失败
当我使用 Item 方法和整数键时,PowerShell 将整数键解释为索引而不是键:
$fooInt=[ordered]@{}
$fooInt.add(12,1)
$fooInt.add(24,2)
write-host ("first item=" + $fooInt.Item(12))
write-host ("second item=" + $fooInt.Item(24))
输出:
Exception getting "Item": "Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
At line:8 char:1
+ write-host ("first item=" + $fooInt.Item(12))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], GetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenGetting
Exception getting "Item": "Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
At line:9 char:1
+ write-host ("second item=" + $fooInt.Item(24))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], GetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenGetting
如何使用整数键访问 PowerShell 哈希表中的值?
最佳答案
哈希表中的键是对象,而不是字符串。当您尝试访问 key 时 "12"
与整数 12
,它无法找到该条目,因为键不匹配。
但是,您没有使用标准哈希表,而是使用具有不同 Item
的有序哈希表。方法,因为它可以通过键或索引工作。如果要使用有序哈希表访问整数键,则需要使用不同的语法:
$hash.12
如果使用数组访问器语法:
$hash[12]
它将尝试返回列表中的第 13 项。
您可以使用
Get-Member
观察这些对象之间的差异。 :$orderedHash | Get-Member Item
TypeName: System.Collections.Specialized.OrderedDictionary
Name MemberType Definition
---- ---------- ----------
Item ParameterizedProperty System.Object Item(int index) {get;set;}, System.Object Item(System.Object key) {get;set;}
$hash | Get-Member Item
TypeName: System.Collections.Hashtable
Name MemberType Definition
---- ---------- ----------
Item ParameterizedProperty System.Object Item(System.Object key) {get;set;}
经过更多的实验,这只是
int32
的情况。类型。如果您使用不同的类型定义和访问它,它将起作用,因为它不再匹配重载 int
签名:$hash = [ordered]@{
([uint32]12) = 24
}
$hash[[uint32]12]
> 24
关于powershell - 如何使用整数键访问有序 PowerShell 哈希表中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51686271/