函数的返回值 [英] Return values of functions
问题描述
我有两个功能:
Function1
{
Function2
return 1
}
Function2
{
return 0
}
执行Function1
后,它应该返回1
,但是它返回0
.为什么会这样?
After executing Function1
it should return 1
, but it returns 0
. Why is that?
推荐答案
PowerShell的返回值"并不能像您习惯使用其他语言那样.要记住的重要一点是所有输出被捕获并返回. return
语句基本上只是一个逻辑出口点.
PowerShell "return values" don't really work the way you'd be used to from other languages. The important thing to remember is that all output is captured and returned. The return
statement is basically just a logical exit point.
例如:
Function Return-Zero {
return 0
}
Function Return-One {
Return-Zero
return 1
}
Return-One
由于Return-Zero
的返回值未存储在变量中,因此它是输出的一部分.运行上面的命令将得到输出:
Since the return value of Return-Zero
was not stored in a variable, it is part of the output. Running the above will have the output:
0
1
...这可能就是您得到的.如果将Return-Zero
的返回值存储在变量中,则它不属于输出.
...which is probably what you're getting. If you store the return of Return-Zero
in a variable, it is not part of the output.
Function Return-Zero {
return 0
}
Function Return-One {
$var = Return-Zero
return $var
}
Return-One
上面的输出是0
.
这篇关于函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!