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

vik*_*ata 0 powershell types hashtable int32

看来PowerShell hashtable(@{})默认是string→string的映射.但是我希望我的价值类型Int32能让我对它进行计算.

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

zet*_*t42 8

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

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

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

请注意,Dictionary以这种方式创建的 a 具有区分大小写的键,而 aHashtable的键不区分大小写。

$dict['a'] = 42
$dict['A'] = 21  # Creates a 2nd entry!
Run Code Online (Sandbox Code Playgroud)

要像 a 一样Dictionary 不区分大小写,必须通过将 a 传递给构造函数Hashtable来以不同的方式创建它:StringComparerDictionary

$dict['a'] = 42
$dict['A'] = 21  # Creates a 2nd entry!
Run Code Online (Sandbox Code Playgroud)


Ans*_*ers 5

Hashtables将键映射到值.键和值的类型并不重要.

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

如果字符串中有整数并希望将其指定为整数,则只需将其转换为赋值:

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