如何为哈希表指定数据类型?

How to specify data type for hashtable?

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

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

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

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

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

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

如果您在字符串中有一个整数并想将其赋值为整数,您可以简单地在赋值时将其强制转换:

PS C:\> <b>$ht[3] = [int]'23'</b>
PS C:\> <b>$ht.Keys | % {$fmt -f $_, $_.GetType().Name, $ht[$_], $ht[$_].GetType().Name}</b>
2 [String]      -> 42 [Int32]
3 [Int32]       -> 23 [Int32]
1 [Int32]       -> foo [String]

Hashtable 的替代方法是 Dictionary,它允许显式指定键和值的类型。

接下来,将创建一个包含 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"