我正在尝试将函数返回的值赋给变量,但变量仍为null。为什么呢?
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()
答案 0 :(得分:4)
需要注意两件事 - 当您在PowerShell中调用cmdlet或函数时,位置参数不是以逗号分隔的:
'<controller:\w+>/<id:\d+>' => '<controller>',
其次,PowerShell非常渴望枚举你在管道中传递的所有数组,所以当你这样做时:
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尝试输出arraylist中的所有单独项目,因为它是空的,所以不会返回任何内容!
您可以通过使用一元数组运算符(return New-Object System.Collections.ArrayList
)将ArrayList包装在数组中来避免这种情况:
,