Вызов конструктора с аргументом Array от Powershell
Я новичок в PowerShell и знаю С# умеренно хорошо. Недавно я писал эту powershell script и хотел создать 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
Затем я построил googled конструкторы в 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? Ты шутишь, что ли? Спасибо.
Ответы
Ответ 1
Это должно работать:
[System.Collections.Generic.HashSet[string]]$allset = $azAZ
UPDATE:
Чтобы использовать массив в конструкторе, массив должен быть строго типизирован. Вот пример:
[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
Ответ 2
попробуйте вот так:
C:\> $allset = New-Object System.Collections.Generic.HashSet[string]
C:\> $allset.add($azAZ)
True