2012-02-03 127 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