我可以在powershell中使用System.Core.dll/System.Collections.Generic.HashSet吗?

nic*_*ick 12 .net powershell .net-3.5

我想在powershell脚本中使用HashSet.我想我已经弄清楚如何通过执行以下方式实例化通用集合对象:

[type] $strType = "string"
$listClass = [System.Collections.Generic.List``1]
$listObject = $base.MakeGenericType(@($t))
$myList = New-Object $setObject
Run Code Online (Sandbox Code Playgroud)

这适用于列表和词典,但是当我尝试创建HashSet时,我得到:

Unable to find type [System.Collections.Generic.HashSet`1]: make sure that the assembly containing this type is loaded.
Run Code Online (Sandbox Code Playgroud)

所以看起来我现在需要加载System.Core.dll但我似乎无法使用powershell加载该程序集.例如,调用[System.Reflection.Assembly] :: LoadWithPartialName("System.Core")会导致此异常:

"LoadWithPartialName" with "1" argument(s): "Could not load file or assembly 'System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified."
Run Code Online (Sandbox Code Playgroud)

有什么指针吗?

Kei*_*ill 22

PowerShell 2.0通过以下方式简化:1)添加Add-Type cmdlet以加载程序集; 2)更新语法以使指定封闭的泛型类型名称更简单,例如:

PS> Add-Type -AssemblyName System.Core
PS> $h = new-object 'System.Collections.Generic.HashSet[string]'
PS> $h.Add('f')
True
Run Code Online (Sandbox Code Playgroud)

  • 是的,但您需要将参数类型指定为`[Collections.Generic.HashSet [string]]`替换您需要存储在hashset中的类型的字符串. (2认同)