返回带/不带括号的函数调用的结果

时间:2013-07-19 10:27:28

标签: powershell powershell-v3.0

为什么以下代码中F和G的返回值存在差异?

Function F {
    Return (New-Object Collections.Generic.LinkedList[Object])
}

Function G {
    Return New-Object Collections.Generic.LinkedList[Object]
}

Function Write-Type($x) {
    If($null -eq $x) {
        Write-Host "null"
    } Else {
        Write-Host $x.GetType()
    }
}

Write-Type (F) # -> null
Write-Type (G) # -> System.Collections.Generic.LinkedList`1[System.Object]

据我了解,如果函数返回某种空集合,PowerShell会将其“展开”为null,因此F会执行我期望的操作。但是G会发生什么?

编辑:正如JPBlanc所指出的,只有PowerShell 3.0表现出这种差异。在2.0中,两行都打印null。改变了什么?

2 个答案:

答案 0 :(得分:3)

抱歉,我没有正确读出您的问题,因为F正在使用()来评估该功能。那么Write-Type函数的结果在PowerShell V2.0中对我来说是一样的。

所以,在PowerShell 3.0中我遇到了你的问题。

现在使用:

Trace-Command -name TypeConversion -Expression {Write-Type (F)} -PSHost

Versus

Trace-Command -name TypeConversion -Expression {Write-Type (G)} -PSHost

据我所知,在返回对象之前生成以下

之前的()
 Converting "Collections.Generic.LinkedList" to "System.Type".
     Conversion to System.Type
         Conversion to System.Type
             Could not find a match for "System.Collections.Generic.LinkedList".
         Could not find a match for "Collections.Generic.LinkedList".
 Converting "Collections.Generic.LinkedList`1" to "System.Type".
     Conversion to System.Type
         Conversion to System.Type
             Found "System.Collections.Generic.LinkedList`1[T]" in the loaded assemblies.
 Converting "Object" to "System.Type".
     Conversion to System.Type
         Conversion to System.Type
             Found "System.Object" in the loaded assemblies.

答案 1 :(得分:0)

说到Powershell功能,“返回”的功能就是早期退出功能。

我查看了Bruce P的书“Powershell in action”第262页,它说:

“那么,为什么Powershell需要一个return语句?答案是,流程控制。有时你想提前退出一个函数。如果没有return语句,你必须编写复杂的条件语句来让流量控制到达终点......“

Keith Hill也有一个非常好的博客谈论这个:http://rkeithhill.wordpress.com/2007/09/16/effective-powershell-item-7-understanding-output/

“......”返回$ Proc“不意味着只输出函数是$ Proc变量的内容。实际上这个结构在语义上等同于“$ PROC;返回“。.....”

基于此,如果您更改这样的功能代码,脚本输出是相同的:

Function F {
    (New-Object Collections.Generic.LinkedList[Object])
    Return 
}

Function G {
   New-Object Collections.Generic.LinkedList[Object]
    Return 
}

此行为与传统语言不同,因此会引起一些混淆。

相关问题