13

如何在 PowerShell 2 中创建列表?我试过这些:

[activator]::createinstance(([type]'system.collections.generic.list`1').makegenerictype([string]))


[activator]::createinstance(([type]'system.collections.generic.list`1').makegenerictype([string]))

我得到的只是一无所有。怎么了?

我正在运行 XP SP3,如果重要的话

4

2 回答 2

19

试试这个:

PS> $list = New-Object 'System.Collections.Generic.List[string]'
PS> $list.Add('foo')
PS> $list
foo

PS> $d = New-Object 'System.Collections.Generic.Dictionary[string,datetime]'
PS> $d.Add('moonshot', [datetime]'7/20/1969')
PS> $d['moonshot']

Sunday, July 20, 1969 12:00:00 AM
于 2010-01-21T16:48:22.113 回答
3

如果您尝试基于字符串创建列表,请尝试以下操作:

New-Object 'System.Collections.Generic.List[system.string]'

请注意,您必须指定'system.string'(至少在我的comp ;))。如果您只使用“字符串”,则会引发异常。

[61]: New-Object 'System.Collections.Generic.List[string]'
New-Object : Cannot find type [System.Collections.Generic.List[string]]: make sure the assembly containing this type is loaded.
At line:1 char:11
+ New-Object <<<<  'System.Collections.Generic.List`1[string]'
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
于 2010-01-21T15:07:05.133 回答