5

Why is there a difference in the return values of F and G in the following code?

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]

As far as I understand, if a function returns some kind of empty collection, PowerShell will "unwrap" it into null, and so F does what I expect. But what's going on with G?

Edit: As pointed out by JPBlanc, only PowerShell 3.0 exhibits this difference. In 2.0, both lines print null. What changed?

4

2 回答 2

3

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

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

现在使用:

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

相对

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.
于 2013-07-19T10:30:47.267 回答
0

当谈到 Powershell 函数时,“return”所做的就是提前退出函数。

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

“那么,为什么 Powershell 需要 return 语句?答案是,流控制。有时你想提前退出函数。如果没有 return 语句,你必须编写复杂的条件语句才能达到流控制结束...”

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

"......"return $Proc" 并不意味着函数只输出 $Proc 变量的内容。实际上这个构造在语义上等价于 "$Proc; 返回”。 .....”

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

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

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

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

于 2013-07-19T14:01:42.543 回答