PowerShell 函数不会返回对象 [英] PowerShell function won't return object
问题描述
我有一个创建通用列表的简单函数:
I have a simple function that creates a generic List:
function test()
{
$genericType = [Type] "System.Collections.Generic.List``1"
[type[]] $typedParameters = ,"System.String"
$closedType = $genericType.MakeGenericType($typedParameters)
[Activator]::CreateInstance($closedType)
}
$a = test
问题是无论我尝试什么, $a
始终为空.如果我在函数之外执行相同的代码,它可以正常工作.
The problem is that $a
is always null no matter what I try. If I execute the same code outside of the function it works properly.
想法?
推荐答案
恕我直言,这是陷阱 #1.如果您从以某种方式可枚举的函数中返回一个对象(我不确切知道是否实现 IEnumerable
是唯一的情况),PowerShell 会展开该对象并返回其中的项目.
IMHO that's pitfall #1. If you return an object from the function that is somehow enumerable (I don't know exactly if implementing IEnumerable
is the only case), PowerShell unrolls the object and returns the items in that.
您新创建的列表是空的,因此没有返回任何内容.要使其工作,只需使用此:
Your newly created list was empty, so nothing was returned. To make it work just use this:
,[Activator]::CreateInstance($closedType)
这将创建一个展开的单项数组,并将该项(通用列表)分配给 $a
.
That will make an one item array that gets unrolled and the item (the generic list) is assigned to $a
.
更多信息
以下是类似问题的列表,可帮助您了解正在发生的事情:
Here is list of similar question that will help you to understand what's going on:
注意:不需要用括号声明函数头.如果需要添加参数,函数如下:
Note: you dont need to declare the function header with parenthesis. If you need to add parameters, the function will look like this:
function test {
param($myParameter, $myParameter2)
}
或
function {
param(
[Parameter(Mandatory=true, Position=0)]$myParameter,
... again $myParameter2)
...
这篇关于PowerShell 函数不会返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!