Powershell中Generic Type的泛型类型 [英] Generic type of Generic Type in Powershell

查看:79
本文介绍了Powershell中Generic Type的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Powershel 中的泛型非常令人困惑.要实例化一个简单的 List,您需要拿着手鼓四处跳舞:

Well generics in Powershel are quite confusing. To instantiate a simple List you need to dance around with a tambourine:

$type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$type= $type.MakeGenericType("System.string" -as "Type")
$o = [Activator]::CreateInstance($type)

但是如果我需要更复杂的东西怎么办:<Dictionary<string,List<Foo>> 例如

But what if I need something a bit more complex like: <Dictionary<string,List<Foo>> for example

或者例如这里:Dictionary>

$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 )

推荐答案

虽然您可以深入研究 CLR 内部表示并让自己的生活变得艰难,但您不必:

While you can delve into CLR internal representations and make life hard for yourself, you don't have to:

$dict = new-object 'collections.generic.dictionary[string,int]'
$dict.add("answer", 42)

想要类型文字表示吗?

[collections.generic.dictonary[string,int]]

完成.泛型类型参数怎么样?

Done. How about generic type parameters?

$dictOfList = new-object 'collections.generic.dictionary[string,
    [collections.generic.list[int]]]'

完成.

然而,有一个不幸的问题.在 PowerShell 2.0 中,将 BCL 和第 3 方类型作为类型参数混合和匹配时会出现错误.后者需要装配合格:

However, there's an unfortunate catch. In PowerShell 2.0, there's a bug when you mix and match BCL and 3rd party types as type parameters. The latter need to be assembly qualified:

# broken over two lines for clarity with backtick escape
$o = new-object ('collections.generic.dictionary[[{0}],[{1}]]' -f `
        [type1].fullname, [type2].fullname)

希望这会有所帮助.在 PowerShell 3.0 中,此问题已得到修复.

Hope this helps. In PowerShell 3.0, this has been fixed.

这篇关于Powershell中Generic Type的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆