我是powershell的初学者,并且对C#适度了解。最近我写了这个powershell脚本,并想创建一个Hashset。所以我写了($ azAz是一个数组)
[System.Collections.Generic.HashSet[string]]$allset = New-Object System.Collections.Generic.HashSet[string]($azAZ)
并按下跑步。我收到了这条消息:
New-Object : Cannot find an overload for "HashSet`1" and the argument count: "52".
At filename.ps1:10 char:55
+ [System.Collections.Generic.HashSet[string]]$allset = New-Object System.Collecti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
然后,我使用数组参数在powershell中搜索构造函数,并将代码更改为:
[System.Collections.Generic.HashSet[string]]$allset = New-Object System.Collections.Generic.HashSet[string](,$azAZ)
不知何故,我现在收到这条消息:
New-Object : Cannot find an overload for "HashSet`1" and the argument count: "1".
At C:\Users\youngvoid\Desktop\test5.ps1:10 char:55
+ [System.Collections.Generic.HashSet[string]]$allset = New-Object System.Collecti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
找不到HashSet的重载和参数count 1?你在跟我开玩笑吗?感谢。
答案 0 :(得分:19)
这应该有效:
[System.Collections.Generic.HashSet[string]]$allset = $azAZ
更新:
要在构造函数中使用数组,必须强类型化数组。这是一个例子:
[string[]]$a = 'one', 'two', 'three'
$b = 'one', 'two', 'three'
# This works
$hashA = New-Object System.Collections.Generic.HashSet[string] (,$a)
$hashA
# This also works
$hashB = New-Object System.Collections.Generic.HashSet[string] (,[string[]]$b)
$hashB
# This doesn't work
$hashB = New-Object System.Collections.Generic.HashSet[string] (,$b)
$hashB
答案 1 :(得分:1)
尝试这样:
C:\> $allset = New-Object System.Collections.Generic.HashSet[string]
C:\> $allset.add($azAZ)
True