无法将字符串设置为我的哈希表的键
Cannot set a string as a key for my hashtable
我正在尝试将此字符串设置为我的密钥:
a -long " string that - has. double and single quotes and dashes and dots
此字符串是 String Builder ToString() 方法的产物。
哈希表初始化如下:$myHashtable = @{ }
这是错误:无法将值“stringAbove”转换为类型“System.Int32”。错误:“输入字符串的格式不正确。”
我尝试用反引号转义双引号。但是还是报同样的错误。
$resultFromToString = $myBuilder.ToString()
$myHashtable[$resultFromToString] = @{
One = $one;
Two = $two;
}
错误消息暗示 $myHashtable
包含一个 array,而不是 hashtable.
- 要确定
$myHashtable
的实际类型,执行$myHashtable.GetType()
或
Get-Member -InputObject $myHashtable
此示例表明您的字符串没有问题,因为 具有 任何 值的字符串 - 甚至 ''
- 都可以用作哈希表键:
$myHashtable = @{} # Initialize.
$myHashtable['a - long string that has " and '' quotes and - and .'] = 'foo'
$myHashtable # Output
输出:
Name Value
---- -----
a - long string that has " an… foo
至于你试过的:
相比之下,如果 $myHashtable
是一个 数组 (无论其 元素 的类型如何),您的症状表面,具有 any 字符串值(无法转换为整数),假设 只有 integers 可以用作数组指数:
$myHashtable = @{}, @{} # !! ARRRAY (of hashtables)
$myHashtable['some key'] = 'foo' # !! FAILS
错误输出:
Cannot convert value "some key" to type "System.Int32". Error: "Input string was not in a correct format."
请注意,正如错误消息所提示的那样,PowerShell 会自动尝试将字符串索引 转换为整数,因此类似下面的内容会 工作,也许令人惊讶:
# Same as:
# $myHashtable[0] = 'foo'
# because PowerShell automatically converts to [int]
$myHashtable[' -0 '] = 'foo'
我正在尝试将此字符串设置为我的密钥:
a -long " string that - has. double and single quotes and dashes and dots
此字符串是 String Builder ToString() 方法的产物。
哈希表初始化如下:$myHashtable = @{ }
这是错误:无法将值“stringAbove”转换为类型“System.Int32”。错误:“输入字符串的格式不正确。”
我尝试用反引号转义双引号。但是还是报同样的错误。
$resultFromToString = $myBuilder.ToString()
$myHashtable[$resultFromToString] = @{
One = $one;
Two = $two;
}
错误消息暗示 $myHashtable
包含一个 array,而不是 hashtable.
- 要确定
$myHashtable
的实际类型,执行$myHashtable.GetType()
或Get-Member -InputObject $myHashtable
此示例表明您的字符串没有问题,因为 具有 任何 值的字符串 - 甚至 ''
- 都可以用作哈希表键:
$myHashtable = @{} # Initialize.
$myHashtable['a - long string that has " and '' quotes and - and .'] = 'foo'
$myHashtable # Output
输出:
Name Value
---- -----
a - long string that has " an… foo
至于你试过的:
相比之下,如果 $myHashtable
是一个 数组 (无论其 元素 的类型如何),您的症状表面,具有 any 字符串值(无法转换为整数),假设 只有 integers 可以用作数组指数:
$myHashtable = @{}, @{} # !! ARRRAY (of hashtables)
$myHashtable['some key'] = 'foo' # !! FAILS
错误输出:
Cannot convert value "some key" to type "System.Int32". Error: "Input string was not in a correct format."
请注意,正如错误消息所提示的那样,PowerShell 会自动尝试将字符串索引 转换为整数,因此类似下面的内容会 工作,也许令人惊讶:
# Same as:
# $myHashtable[0] = 'foo'
# because PowerShell automatically converts to [int]
$myHashtable[' -0 '] = 'foo'