首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell中泛型类型的泛型类型

Powershell中泛型类型的泛型类型
EN

Stack Overflow用户
提问于 2012-08-16 02:39:50
回答 4查看 10.3K关注 0票数 13

Powershel中的泛型非常令人困惑。要实例化一个简单的列表,您需要使用一个手鼓:

代码语言:javascript
复制
$type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$type= $type.MakeGenericType("System.string" -as "Type")
$o = [Activator]::CreateInstance($type)

但是,如果我需要一些更复杂的东西,比如:<Dictionary<string,List<Foo>>

或者例如这里:Dictionary<string,List<string>>

代码语言:javascript
复制
$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 )
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-08-16 04:53:01

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

代码语言:javascript
复制
$dict = new-object 'collections.generic.dictionary[string,int]'
$dict.add("answer", 42)

想要类型文字表示吗?

代码语言:javascript
复制
[collections.generic.dictonary[string,int]]

好了。泛型类型参数呢?

代码语言:javascript
复制
$dictOfList = new-object 'collections.generic.dictionary[string,
    [collections.generic.list[int]]]'

好了。

然而,这里有一个不幸的陷阱。在PowerShell 2.0中,当您混合和匹配BCL和第三方类型作为类型参数时,存在一个错误。后者需要符合程序集要求:

代码语言:javascript
复制
# 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中,已修复此问题。

票数 26
EN

Stack Overflow用户

发布于 2012-08-16 04:00:57

是的,这似乎是可能的,但就像PS中的几乎所有其他东西一样,这也是非常丑陋的。以下是真实世界的示例:

$requestItemsType是一个Dictionary<string, List<Amazon.DynamoDB.Model.WriteRequest>>

代码语言:javascript
复制
$wrt = ("System.Collections.Generic.List``1" -as "Type") 
$wrt = $wrt.MakeGenericType( @( ("Amazon.DynamoDB.Model.WriteRequest" -as "Type")))

$requestItemsType = ("System.Collections.Generic.Dictionary"+'`'+"2") -as "Type"
$requestItemsType = $requestItemsType.MakeGenericType( @( ("System.string" -as "Type"), ($wrt)))
$ri = [Activator]::CreateInstance($requestItemsType)
$ri.Add("TaskLog",$writeRequests)
票数 0
EN

Stack Overflow用户

发布于 2013-07-26 04:44:09

如果你正在创建一个定义了自定义类型的字典,上面的例子就不需要那么复杂了:

代码语言:javascript
复制
$propertiesType = ("System.Collections.Generic.Dictionary"+'`'+"2") -as "Type"
$propertiesType = $propertiesType.MakeGenericType( @( ("System.string" -as "Type"), ("Namespace.CustomType" -as "Type")))
$properties = [Activator]::CreateInstance($propertiesType)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11975130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档