PowerShell 版本:5.x、6
我正在尝试创建 的新对象System.Collections.Generic.Dictionary
,但失败了。
我尝试了以下“版本”:
> $dictionary = new-object System.Collections.Generic.Dictionary[[string],[int]]
New-Object : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'ComObject'. Specified method is not supported.
At line:1 char:25
+ ... ry = new-object System.Collections.Generic.Dictionary[[string],[int]]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.NewObjectCommand
> $dictionary = new-object System.Collections.Generic.Dictionary[string,int]
New-Object : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'ComObject'. Specified method is not supported.
At line:1 char:25
+ ... ionary = new-object System.Collections.Generic.Dictionary[string,int]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.NewObjectCommand
Run Code Online (Sandbox Code Playgroud)
我知道我可以在 PowerShell 下使用哈希表,但我想知道如何通过上述声明创建字典。
我错过了什么?
谢谢
除了接受的答案之外,还可以使用下面代码块中的语法来初始化字典,其中:
$dictionary = [System.Collections.Generic.Dictionary[string,int]]::new()
Run Code Online (Sandbox Code Playgroud)
...其中string
和int
是 .NET 类型。
使用的类型名称System.Collections.Generic.Dictionary[[string],[int]]
包含一个逗号。通过创建和初始化数组:
要创建和初始化数组,请为变量分配多个值。存储在数组中的值用逗号分隔……
因此,您需要对逗号进行转义(阅读about_Escape_Characters和about_Quoting_Rules帮助主题)。还有更多选择:
在 Windows PowerShell 中,转义字符是反引号(
`
),也称为重音符(ASCII 96)。
$dictionary = new-object System.Collections.Generic.Dictionary[[string]`,[int]]
Run Code Online (Sandbox Code Playgroud)
引号用于指定文字字符串。您可以将字符串括在单引号(
'
) 或双引号 ("
) 中。
$dictionary = new-object "System.Collections.Generic.Dictionary[[string],[int]]"
Run Code Online (Sandbox Code Playgroud)
或者
$dictionary = new-object 'System.Collections.Generic.Dictionary[[string],[int]]'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3253 次 |
最近记录: |