2012-02-03 12 views
11

Soy un principiante en PowerShell y conozco C# moderadamente bien. Recientemente estaba escribiendo este script de PowerShell y quería crear un Hashset. Así que escribí ($ azAz es una matriz)Llamando al Constructor con Array Argumento de Powershell

[System.Collections.Generic.HashSet[string]]$allset = New-Object System.Collections.Generic.HashSet[string]($azAZ) 

y presiona ejecutar. Tengo este mensaje:

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 

Entonces, busqué en Google constructores en PowerShell con parámetros de matriz y ha cambiado el código para:

[System.Collections.Generic.HashSet[string]]$allset = New-Object System.Collections.Generic.HashSet[string](,$azAZ) 

De alguna manera, ahora sale este mensaje:

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 

¿No puede encontrar una sobrecarga para HashSet y el argumento count 1? ¿Me estás tomando el pelo? Gracias.

+0

Por qué la coma en (, $ AZAZ) ?? –

+0

no lo sé, lo obtuve de una búsqueda en google. Ni siquiera leí el artículo, pero al menos consiguió que powershell tratara a $ azAZ como 1 argumento. Tal vez es porque la coma indica argumentos separados? – irisjay

+0

Es porque la coma es el operador de creación de la matriz, por lo que hace de $ azAZ una matriz con un elemento único de $ azAZ. Creo que @ ($ azAZ) es una forma más clara de crear una matriz de matriz. – Massif

Respuesta

18

Esto debería funcionar:

[System.Collections.Generic.HashSet[string]]$allset = $azAZ 

ACTUALIZACIÓN:

utilizar una matriz en el constructor de la matriz debe ser inflexible. Aquí está un ejemplo:

[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

gracias, funcionó. De todos modos, ¿qué error había en mi código? – irisjay

+0

Creo que la inicialización de las colecciones fue azúcar sintáctica que se agregó en C# 3. El compilador primero crea la colección, luego agrega los elementos detrás de las escenas. PowerShell simplemente no tiene sintaxis para esto. – Rynant

+0

pero la clase hashset contiene el constructor HashSet (IEnumerable ) con 1 argumento, simplemente marque msdn. – irisjay

1

oportunidad como esta:

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

su método también funciona, pero tenía la intención de usar el constructor hashset. Sin embargo, su método es bonito y elegante – irisjay

+0

espera, su $ allset.add ($ azAZ) agrega todos los elementos en $ azAZ como 1 elemento. algo definitivamente está mal aquí. – irisjay

+0

Sí, el complemento() hace esto. No entendí tus necesidades. La forma correcta de poblar el HasSet de los valores de arry está en la respuesta de Rynant. –

Cuestiones relacionadas