Pergunta

I foram empurrando para o .NET framework em PowerShell, e eu bater em alguma coisa que eu não entendo. Isso funciona bem:

$foo = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
$foo.Add("FOO", "BAR")
$foo

Key                                                         Value
---                                                         -----
FOO                                                         BAR

Este, porém, não:

$bar = New-Object "System.Collections.Generic.SortedDictionary``2[System.String,System.String]"
New-Object : Cannot find type [System.Collections.Generic.SortedDictionary`2[System.String,System.String]]: make sure t
he assembly containing this type is loaded.
At line:1 char:18
+ $bar = New-Object <<<< "System.Collections.Generic.SortedDictionary``2[System.String,System.String]"

Ambos estão no mesmo assembly, então o que eu estou ausente?

Como foi indicado nas respostas, isso é muito bonito apenas um problema com PowerShell v1.

Foi útil?

Solução

dicionário não está definida no mesmo conjunto como SortedDictionary . Uma delas é em mscorlib e outro em system.dll.

É aí que reside o problema. O comportamento atual em PowerShell é que ao resolver os parâmetros genéricos especificado, se os tipos não são nomes de tipo totalmente qualificado, que tipo de assume que eles estão no mesmo conjunto como o tipo genérico que você está tentando criar uma instância.

Neste caso, isso significa que ele está procurando System.String em System.dll, e não em mscorlib, então ele falhar.

A solução é especificar o nome de assembly totalmente qualificado para os tipos de parâmetros genéricos. É extremamente feio, mas funciona:

$bar = new-object "System.Collections.Generic.Dictionary``2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"

Outras dicas

Em PowerShell 2.0 a nova maneira de criar um Dictionary é:

$object = New-Object 'system.collections.generic.dictionary[string,int]'

Existem alguns problemas com os genéricos em PowerShell. Lee Holmes, um dev na equipe PowerShell postou este script para criar Genéricos.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top