【发布时间】:2012-02-26 03:40:37
【问题描述】:
我是 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 和参数计数 1 的重载?你在跟我开玩笑吗?谢谢。
【问题讨论】:
-
为什么是逗号 (, $azAZ) ??
-
我不知道,我是从谷歌搜索得到的。我什至没有通读这篇文章,但至少它让 powershell 将 $azAZ 视为 1 个参数。也许是因为逗号表示单独的参数?
-
因为逗号是数组创建操作符,所以它把$azAZ变成了一个只有$azAZ元素的数组——我认为@($azAZ)是一种更清晰的创建数组的方式——一个数组。
-
显然@($azAZ) 不起作用,“喷溅运算符'@'不能用于引用表达式中的变量”所以必须使用逗号
标签: arrays powershell constructor arguments hashset