Powershel中的泛型非常令人困惑。要实例化一个简单的列表,您需要使用一个手鼓:
$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>>
$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 )发布于 2012-08-16 04:53:01
虽然您可以深入研究CLR内部表示并使自己的生活变得困难,但您不必这样做:
$dict = new-object 'collections.generic.dictionary[string,int]'
$dict.add("answer", 42)想要类型文字表示吗?
[collections.generic.dictonary[string,int]]好了。泛型类型参数呢?
$dictOfList = new-object 'collections.generic.dictionary[string,
[collections.generic.list[int]]]'好了。
然而,这里有一个不幸的陷阱。在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)希望这能有所帮助。在PowerShell 3.0中,已修复此问题。
发布于 2012-08-16 04:00:57
是的,这似乎是可能的,但就像PS中的几乎所有其他东西一样,这也是非常丑陋的。以下是真实世界的示例:
$requestItemsType是一个Dictionary<string, List<Amazon.DynamoDB.Model.WriteRequest>>
$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)发布于 2013-07-26 04:44:09
如果你正在创建一个定义了自定义类型的字典,上面的例子就不需要那么复杂了:
$propertiesType = ("System.Collections.Generic.Dictionary"+'`'+"2") -as "Type"
$propertiesType = $propertiesType.MakeGenericType( @( ("System.string" -as "Type"), ("Namespace.CustomType" -as "Type")))
$properties = [Activator]::CreateInstance($propertiesType)https://stackoverflow.com/questions/11975130
复制相似问题