mar*_*ark 5 powershell hashset
我想HashSet
使用接受集合的构造函数创建一个
但我的尝试都没有成功:
C:\> $c = @(1,2,3,4,5)
C:\> New-Object System.Collections.Generic.HashSet[int]
C:\> New-Object System.Collections.Generic.HashSet[int] -ArgumentList @(,$c)
New-Object : Cannot find an overload for "HashSet`1" and the argument count: "1".
At line:1 char:1
+ New-Object System.Collections.Generic.HashSet[int] -ArgumentList @(,$ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
C:\> New-Object System.Collections.Generic.HashSet[int] -ArgumentList $c
New-Object : Cannot find an overload for "HashSet`1" and the argument count: "5".
At line:1 char:1
+ New-Object System.Collections.Generic.HashSet[int] -ArgumentList $c
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
C:\> New-Object System.Collections.Generic.HashSet[int] -ArgumentList @($c)
New-Object : Cannot find an overload for "HashSet`1" and the argument count: "5".
At line:1 char:1
+ New-Object System.Collections.Generic.HashSet[int] -ArgumentList @($c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
C:\>
Run Code Online (Sandbox Code Playgroud)
有办法做到吗?
我一直在摆弄这个,看起来这有效:
[int[]]$c = 1,2,3,4,5
[System.Collections.Generic.HashSet[int]]::new([System.Collections.Generic.IEnumerable[int]]$c)
Run Code Online (Sandbox Code Playgroud)
您甚至可以省略[System.Collections.Generic.IEnumerable[int]]
此处的部分,然后执行
[int[]]$c = 1,2,3,4,5
[System.Collections.Generic.HashSet[int]]::new($c)
Run Code Online (Sandbox Code Playgroud)
如果不声明数组,因为[int[]]
它不起作用,您会收到错误
无法将“System.Object[]”类型的“System.Object[]”值转换为“System.Collections.Generic.IEnumerable`1[System.Int32]”类型。
通过类型转换[int[]]
,变量的类型c$
并不System.Int32[]
简单System.Object[]
,而这正是构造函数想要的。
希望有帮助