我想在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)
有什么指针吗?
Powershel的仿制药非常令人困惑.要实例化一个简单的列表,你需要用手鼓跳舞:
$type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$type= $type.MakeGenericType("System.string" -as "Type")
$o = [Activator]::CreateInstance($type)
Run Code Online (Sandbox Code Playgroud)
但是,如果我需要更复杂的东西<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 )
Run Code Online (Sandbox Code Playgroud) 我正在尝试Enumerable.ToList()在PowerShell中使用.显然,要做到这一点,我必须明确地将对象转换为IEnumerable<CustomType>,但我无法做到这一点.好像我无法IEnumerable<CustomType>在PowerShell中正确编写.无论IEnumerable<string>和CustomType自身正确的(我想使用自定义类型被称为工作WpApiLib.Page),所以我不知道我该怎么做是错误的.
PS C:\Users\Svick> [Collections.Generic.IEnumerable``1[System.String]]
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False IEnumerable`1
PS C:\Users\Svick> [WpApiLib.Page]
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Page System.Object
PS C:\Users\Svick> [Collections.Generic.IEnumerable``1[WpApiLib.Page]]
Unable to find type [Collections.Generic.IEnumerable`1[WpApiLib.Page]]: make su
re that the assembly containing this type is loaded.
At line:1 char:51
+ [Collections.Generic.IEnumerable``1[WpApiLib.Page]] <<<<
Run Code Online (Sandbox Code Playgroud)