2015-05-31 39 views
1

我在PowerShell中4.0试过这样:powershell:创建一个带语法错误的通用哈希集?

[System.Assembly]::LoadWithPartialName("System.Collections.Generic") 
$m = New-Object '[System.Collections.Generic::HashSet](String)' 
$m.GetType() 

但运行提供了错误。我的用法不正确?我只有两行代码!

Unable to find type [System.Assembly]. Make sure that the assembly that contains this type is loaded. 
At D:\Untitled1.ps1:1 char:1 
+ [System.Assembly]::LoadWithPartialName("System.Collections.Generic") 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
+ CategoryInfo   : InvalidOperation: (System.Assembly:TypeName) [], RuntimeException 
+ FullyQualifiedErrorId : TypeNotFound 

New-Object : Cannot find type [[System.Collections.Generic::HashSet]    (String)]: verify that the assembly containing this type is loaded. 
At D:\Untitled1.ps1:2 char:6 
+ $m = New-Object '[System.Collections.Generic::HashSet](String)' 
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
+ CategoryInfo   : InvalidType: (:) [New-Object],   PSArgumentException 
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand 

You cannot call a method on a null-valued expression. 
At D:\Untitled1.ps1:3 char:1 
+ $m.GetType() 
+ ~~~~~~~~~~~~ 
+ CategoryInfo   : InvalidOperation: (:) [], RuntimeException 
+ FullyQualifiedErrorId : InvokeMethodOnNull 

回答

2

LoadWithPartialName()是在[System.Reflection.Assembly],不[System.Assembly]。此外,您的New-Object语法稍微关闭。

[System.Reflection.Assembly]::LoadWithPartialName("System.Collections.Generic") 
$m = New-Object 'System.Collections.Generic.HashSet[String]' 
$m.GetType() 

参见:http://www.leeholmes.com/blog/2006/08/18/creating-generic-types-in-powershell/

+2

需要注意的是,至少在最新版本的PowerShell的,你应该不需要加载System.Collections.Generic。 –