如何定义函数的返回类型/输出类型 [英] How to define the return type / OutputType of a function
问题描述
为什么下面是变化的类型?
Why is the following changing type?
function SomeFunction($SomeParameter){
return $SomeParameter
}
我想我需要设置返回类型,但如何设置?
I guess I need to set a return type, but how?
一个例子是:
$NewFolder=Join-Path $CurrentFolder -ChildPath $FolderName
$Tmp=SomeFunction($NewFolder)
现在 $Tmp
是一个数组而不仅仅是一个路径
Now $Tmp
is an array and not just a path
推荐答案
您的问题与设计"有关.PowerShell 将分块返回一个数组,以便可以将其转发到 PowerShell 管道.
Your issue is per "design". PowerShell will return an array in chunks so that it can be forwarded the PowerShell pipeline.
示例:
SomeFunction -SomeParameter @(1,2,3,4) | Where-Object { $_ -gt 2 }
如果没有这种行为,就不可能将函数的输出流水线化到另一个函数/cmdlet.
Without this behavior pipelining the output of the function to another function/cmdlet won't be possible.
如果你想返回一个数组,你可以将代码改为:
If you want to return an array you can change to code to:
function SomeFunction($SomeParameter){
<#
# Through the unary operator we can return an array with one entry.
# This entry contains the original array.
#>
,$SomeParameter
}
另一种选择是在调用端使用 @()
:
Another option would be the use of @()
when at the calling side:
function SomeFunction($SomeParameter){
# return to pipelin
$SomeParameter
}
$array = @(SomeFunction -SomeParameter 1,2,3,4)
还有这个 reddit answer 解释了更多细节.
There is also this reddit answer explaining the behavior in more detail.
希望有所帮助.
这篇关于如何定义函数的返回类型/输出类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!