2012-02-03 207 views
11

我是PowerShell的初学者,熟悉C#。最近我正在写这个PowerShell脚本,并想创建一个Hashset。所以我写了($ azAz是一个数组)从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: "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 

然后,我用Google搜索构造函数在数组参数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?你在跟我开玩笑吗?谢谢。

+0

为什么逗号(,$阿扎兹)? – 2012-02-03 14:25:44

+0

我不知道,我从谷歌搜索得到它。我甚至没有阅读过这篇文章,但至少它有把powershell作为1个参数对待$ azAZ的能力。也许这是因为逗号表示单独的论点? – irisjay 2012-02-03 14:51:04

+0

这是因为逗号是数组创建操作符,所以它将$ azAZ变成一个单元素为$ azAZ的数组 - 我认为@($ azAZ)是创建一个数组的单元阵列的更清晰的方法。 – Massif 2012-02-03 15:04:28

回答

18

这应该工作:

[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 
+0

谢谢,它的工作。无论如何,我的代码有什么错误? – irisjay 2012-02-03 14:47:02

+0

我认为初始化集合是在c#3中添加的语法糖。编译器首先创建集合,然后在场景后面添加元素。 PowerShell没有这个语法。 – Rynant 2012-02-03 15:09:14

+0

但哈希集类包含具有1个参数的构造函数HashSet (IEnumerable ),只需检查msdn。 – irisjay 2012-02-03 16:42:33

1

尝试这样的:

C:\> $allset = New-Object System.Collections.Generic.HashSet[string] 
C:\> $allset.add($azAZ) 
True 
+0

你的方法也可以,但我打算使用哈希集构造函数。然而,你的方法是漂亮而优雅的 – irisjay 2012-02-03 14:49:30

+0

等待,你的$ allset.add($ azAZ)将$ azAZ中的所有元素添加为1个元素!这里肯定是错的。 – irisjay 2012-02-03 14:55:10

+0

是的,add()这样做。我误解了你的需求。在Rynant的答案中,从arry值填充HasSet的正确方法是。 – 2012-02-03 15:17:46