为什么函数返回null?

Lie*_*ero 4 powershell

我正在尝试将从函数返回的值分配给变量,但该变量仍然为空。为什么?

function Foo{
    Param([string]$key, 
          [system.collections.generic.dictionary[string,system.collections.arraylist]] $cache)

    if (-not $cache.ContainsKey($key))
    {
        $cache[$key] = New-Object 'system.collections.arraylist'
    }
    $result = $cache[$key]
    return $result #when debugging, this is not null
}

$key = ...
$cache = ...

#EDIT: $result = Foo ($key, $cache)
#Im actually calling it without comma and bracket:
$result = Foo -key $key -cache $cache
$result.GetType()

#results in: You cannot call a method on a null-valued expression.
#At line:1 char:1
#+ $result.GetType()
Run Code Online (Sandbox Code Playgroud)

Mat*_*sen 6

需要注意的两件事 - 当您在 PowerShell 中调用 cmdlet 或函数时,位置参数不是以逗号分隔的:

Foo($key,$cache)             # wrong, you supply a single array as the only argument
Foo -key $key -cache $cache  # correct, named parameter binding
Foo $key $cache              # correct, (implicit) positional parameter binding
Run Code Online (Sandbox Code Playgroud)

其次,PowerShell 非常渴望枚举您沿管道传递的所有数组,因此当您这样做时:

return New-Object System.Collections.ArrayList
Run Code Online (Sandbox Code Playgroud)

PowerShell 尝试输出 arraylist 中的所有单个项,但由于它是空的,因此不会返回任何内容!

您可以通过使用一元数组运算符 ( ,)将 ArrayList 包装在数组中来规避此问题:

return ,$result
Run Code Online (Sandbox Code Playgroud)