powershell - 如何指定哈希表的数据类型?

标签 powershell types hashtable int32

看来 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]

关于powershell - 如何指定哈希表的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30935885/

相关文章:

powershell - 在Powershell输出的文件大小中包含unc路径

powershell - 在PowerShell中验证编号的变量

Powershell 解析包含冒号的属性文件

c++ - 设计一个重新散列函数......如何避免相同的散列?

c# - 多键散列或字典,值列表作为输出

powershell - PowerShell 中的 '@{}' 是什么意思

powershell - powershell Get-Item如何表示目的地是要创建的文件夹?

string - 类型安全的 printf

没有完整类型知识的 Haskell 多态调用

c - 我如何教 vim 语法高亮的附加 C 语言类型?