开发者

Generics in PowerShell 2 not working?

开发者 https://www.devze.com 2022-12-17 06:32 出处:网络
How could I make a List in PowerShell 2? I\'ve tried these: [activator]::createinstance(([type]\'system.collections.generic.list`1\').makegenerictype([string]))

How could I make a List in PowerShell 2? I've tried these:

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

and

[a开发者_高级运维ctivator]::createinstance(([type]'system.collections.generic.list`1').makegenerictype([string]))

and all I get is just nothing. What's going wrong?

I'm running XP SP3, if it matters


Try this:

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


If you try to create a list based on strings, try this:

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

Note that you have to specify 'system.string' (at least on my comp ;) ). If you just use 'string', it throws an exception.

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

精彩评论

暂无评论...
验证码 换一张
取 消