2

默认情况下, PowerShell 哈希表 ( ) 似乎@{}是字符串→字符串的映射。但我希望我的值类型是Int32这样我可以对其进行计算。

声明哈希表变量时如何指定类型信息?

4

2 回答 2

5

哈希表将键映射到值。键和值的类型无关紧要。

PS C:\> $ht = @{}
PS C:\> $ht[1] = 'foo'
PS C:\> $ht['2'] = 42
PS C:\> $ht

Name                           Value
----                           -----
2                              42
1                              foo

PS C:\> $fmt = "{0} [{1}]`t-> {2} [{3}]"
PS C:\> $ht.Keys | % {$fmt -f $_, $_.GetType().Name, $ht[$_], $ht[$_].GetType().Name}
2 [String]      -> 42 [Int32]
1 [Int32]       -> foo [String]

如果您在字符串中有一个整数并希望将其分配为整数,您可以简单地将其转换为赋值:

PS C:\> $ht[3] = [int]'23'
PS C:\> $ht.Keys | % {$fmt -f $_, $_.GetType().Name, $ht[$_], $ht[$_].GetType().Name}
2 [String]      -> 42 [Int32]
3 [Int32]       -> 23 [Int32]
1 [Int32]       -> foo [String]
于 2015-06-19T10:53:40.603 回答
1

另一种方法HashtableDictionary允许显式指定键和值的类型。

在下面,将创建一个包含string键和值的字典:int

[System.Collections.Generic.Dictionary[string, int]] $dict = @{}

$dict['a'] = 42      # Ok
$dict['b'] = '42'    # Ok (implicit type conversion)
$dict['c'] = 'abc'   # Error: Cannot convert value "abc" to type "System.Int32"
于 2020-12-08T16:19:18.407 回答