powershell:创建具有语法错误的通用哈希集?

powershell: creating a generic hashset with syntax error?

我在 powershell 4.0 中试过这个:

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

但是运行给出了错误。我的用法不正确吗?我只有2行代码!

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

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/