如何使用整数键访问有序PowerShell散列表中的值?

Nov*_*Eng 4 powershell hashtable key

我的要求是使用有序哈希表中的那些整数键来存储整数键和访问哈希表值.

什么有效

当我使用字符串键时,没问题:

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"))
Run Code Online (Sandbox Code Playgroud)

输出:

first item=1
second item=2
Run Code Online (Sandbox Code Playgroud)

使用支架失败

当我使用括号时,程序不会抛出异常,但它不返回任何内容:

$fooInt=[ordered]@{}

$fooInt.add(12,1)
$fooInt.add(24,2)

write-host ("first item=" + $fooInt[12])
write-host ("second item=" + $fooInt[24])
Run Code Online (Sandbox Code Playgroud)

输出:

first item=
second item=
Run Code Online (Sandbox Code Playgroud)

使用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))
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

如何使用整数键访问PowerShell哈希表中的值?

The*_*le1 7

它们在哈希表中的键是对象,而不是字符串.当您尝试使用"12"整数访问密钥时12,由于密钥不匹配,因此找不到该条目.

但是,您没有使用标准哈希表,您使用的是有序哈希表,它具有不同的Item方法,因为它可以按键或索引工作.如果要使用有序哈希表访问整数键,则需要使用不同的语法:

$hash.12
Run Code Online (Sandbox Code Playgroud)

如果使用数组访问器语法:

$hash[12]
Run Code Online (Sandbox Code Playgroud)

它会尝试返回列表中的第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;}
Run Code Online (Sandbox Code Playgroud)

经过一些实验,这只是int32类型的情况.如果您使用其他类型定义和访问它,它将起作用,因为它不再匹配重载的int签名:

$hash = [ordered]@{
    ([uint32]12) = 24
}
$hash[[uint32]12]
> 24
Run Code Online (Sandbox Code Playgroud)