我正在尝试将从函数返回的值分配给变量,但该变量仍然为空。为什么?
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()
最佳答案
需要注意的两件事 - 当您在 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
其次,PowerShell 非常渴望枚举您沿管道传递的所有数组,因此当您这样做时:
return New-Object System.Collections.ArrayList
PowerShell 尝试输出 arraylist 中的所有单个项,但由于它是空的,因此不会返回任何内容!
您可以通过使用一元数组运算符 (
,
) 将 ArrayList 包装在数组中来规避此问题:return ,$result
关于powershell - 为什么函数返回null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35206656/