无论如何在powershell中我有以下脚本
function ReturnTrue()
{
write-host "ReturnTrue executed!"
return $true
}
if (ReturnTrue -and ReturnTrue -and ReturnTrue)
{
write-host "ReturnTrue should have executed 3 times"
}
预期输出是看“ReturnTrue已执行!”打印3次,但只打印一次。 C#或Java中的类似代码将执行ReturnTrue()3次。这是什么交易?
答案 0 :(得分:6)
好陷阱!这是代码及其在注释中的解释,该函数还显示其参数:
function ReturnTrue()
{
write-host "ReturnTrue executed with $args!"
return $true
}
# this invokes ReturnTrue once with arguments: -and ReturnTrue -and ReturnTrue
if (ReturnTrue -and ReturnTrue -and ReturnTrue)
{
write-host "ReturnTrue should have executed 1 time"
}
# this invokes ReturnTrue 3 times
if ((ReturnTrue) -and (ReturnTrue) -and (ReturnTrue))
{
write-host "ReturnTrue should have executed 3 times"
}
输出:
ReturnTrue executed with -and ReturnTrue -and ReturnTrue!
ReturnTrue should have executed 1 time
ReturnTrue executed with !
ReturnTrue executed with !
ReturnTrue executed with !
ReturnTrue should have executed 3 times