【发布时间】:2019-01-12 03:39:50
【问题描述】:
我的要求是在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 哈希表中的值?
【问题讨论】:
-
@TessellatingHeckler:不 - 请参阅上面标记为 Using Brackets Fails 的更新
-
啊,我明白了;另一个(更糟糕的)选择是使用反射来挑选
get_Item()的正确重载并调用它。$fooInt.GetType().GetMethods().where{$_.Name -eq 'get_Item' -and $_.GetParameters().name -eq 'Key'}.Invoke($fooInt, 'Public', $null, 1, $null)
标签: powershell key hashtable