4

当我通过引用一个函数来传递一个哈希表时,我遇到了一个障碍。我怎样才能解决这个问题?

Function AllMyChildren {
    param (
        [ref]$ReferenceToHash
    }
    get-childitem @ReferenceToHash.Value
    #  etc.etc.
}
$MyHash = @{
    'path' = '*'
    'include' = '*.ps1'
    'name' = $null
}
AllMyChildren ([ref]$MyHash)

结果:错误(“Splatted 变量不能用作属性或数组表达式的一部分。将表达式的结果分配给临时变量,然后改为 splat 临时变量。”)。

试图这样做:

$newVariable = $ReferenceToHash.Value
get-childitem @NewVariable

这确实有效,并且根据错误消息似乎是正确的。在这种情况下,它是首选语法吗?

4

1 回答 1

4

1) 传递哈希表(或任何类的实例,即引用类型)[ref]没有意义,因为它们本身总是通过引用传递。[ref]与值类型(标量和结构实例)一起使用。

2) splatting 运算符可以直接应用于变量,而不是表达式。

因此,为了解决问题,只需在函数中传递哈希表即可:

Function AllMyChildren {
    param (
        [hashtable]$ReferenceToHash # it is a reference itself
    )
    get-childitem @ReferenceToHash
    #  etc.etc.
}
$MyHash = @{
    'path' = '*'
    'include' = '*.ps1'
    'name' = $null
}
AllMyChildren $MyHash
于 2012-11-11T15:33:24.720 回答