我有一个简单的函数来创建一个通用列表:
function test()
{
$genericType = [Type] "System.Collections.Generic.List``1"
[type[]] $typedParameters = ,"System.String"
$closedType = $genericType.MakeGenericType($typedParameters)
[Activator]::CreateInstance($closedType)
}
$a = test
问题是$a
无论我尝试什么,它总是为空。如果我在函数之外执行相同的代码,它将正常工作。
想法?
恕我直言,这是陷阱#1。如果您从函数返回一个可枚举的对象(我不知道是否确切地实现IEnumerable
是唯一的情况),PowerShell 展开该对象并返回其中的项目。
您新创建的列表是空的,因此没有返回任何内容。要使其工作,只需使用以下命令:
,[Activator]::CreateInstance($closedType)
这将生成一个展开的单项数组,并将该项(通用列表)分配给$a
.
更多信息
以下是类似问题的列表,可帮助您了解正在发生的事情:
- Powershell 陷阱 https://stackoverflow.com/questions/803521/powershell-pitfalls
- 避免 Powershell 中不可知的锯齿状数组扁平化 https://stackoverflow.com/questions/2463190/avoiding-agnostic-jagged-array-flattening-in-powershell
- PowerShell 函数中返回 DataSet/DataTable 的奇怪行为 https://stackoverflow.com/questions/1918190/strange-behavior-in-powershell-function-returning-dataset-datatable
- 是什么决定了 Powershell 管道是否展开集合? https://stackoverflow.com/questions/1827862/what-determines-whether-the-powershell-pipeline-will-unroll-a-collection
Note:您不需要用括号声明函数头。如果需要添加参数,函数将如下所示:
function test {
param($myParameter, $myParameter2)
}
or
function {
param(
[Parameter(Mandatory=true, Position=0)]$myParameter,
... again $myParameter2)
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)