Powershel的仿制药非常令人困惑.要实例化一个简单的列表,你需要用手鼓跳舞:
$type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$type= $type.MakeGenericType("System.string" -as "Type")
$o = [Activator]::CreateInstance($type)
Run Code Online (Sandbox Code Playgroud)
但是,如果我需要更复杂的东西<Dictionary<string,List<Foo>>,例如:
或者例如这里: Dictionary<string,List<string>>
$listType = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$listType = $listType.MakeGenericType("System.string" -as "Type")
$L = [Activator]::CreateInstance($listType)
$dicType = ("System.Collections.Generic.Dictionary"+'`'+"2") -as "Type"
#the next line is problematic
$dicType = $dicType.MakeGenericType(
@( ("system.string" -as "Type"),
("System.Collections.Generic.List" as "Type)) # and that's of course wrong
)
$D = [Activator]::CreateInstance($dicType )
Run Code Online (Sandbox Code Playgroud)
x0n*_*x0n 19
虽然你可以深入到CLR内部表示,使生活困难的自己,你不要有到:
$dict = new-object 'collections.generic.dictionary[string,int]'
$dict.add("answer", 42)
Run Code Online (Sandbox Code Playgroud)
想要一个类型的文字表示?
[collections.generic.dictonary[string,int]]
Run Code Online (Sandbox Code Playgroud)
完成.泛型类型参数怎么样?
$dictOfList = new-object 'collections.generic.dictionary[string,
[collections.generic.list[int]]]'
Run Code Online (Sandbox Code Playgroud)
完成.
但是,有一个不幸的问题.在PowerShell 2.0中,将BCL和第三方类型混合并匹配为类型参数时会出现错误.后者需要装配合格:
# broken over two lines for clarity with backtick escape
$o = new-object ('collections.generic.dictionary[[{0}],[{1}]]' -f `
[type1].fullname, [type2].fullname)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.在PowerShell 3.0中,这已得到修复.
| 归档时间: |
|
| 查看次数: |
8309 次 |
| 最近记录: |