我想一个数组传递给函数并填写,然后打印功能之外的结果。 但第一函数不能识别数组列表对象我传递给它。
主文件:
. $funcFile
$myParam = "Hello World"
$myObj = getMyObject $myParam
$myObj.myArrayList.Count # This works (outputs 0)
myFunction2 ($myObj.myArrayList)
$myObj.myArrayList.Count # This also works (outputs 0)
fncFile:
function getMyObject([String] $myParam) {
$myObj = @{
"myArrayList" = (New-Object System.Collections.ArrayList)
}
return $myObj
}
function myFunction2 ([System.Collections.ArrayList] $myArr){
$myArr.Count # This doesn't work (outputs nothing)
if($myArr -eq $null) {
Write-Host "Array List Param is null" # This condition is FALSE - nothing is printed
}
}
我究竟做错了什么? 我如何可以使用函数2和其他内部函数相同的ArrayList?
如果你想传递一个变量并修改它在功能和使用效果有2种方式:
按值传递:
$arr = New-Object System.Collections.ArrayList
function FillObject([System.Collections.ArrayList]$array, [String] $myParam) {
return $array.Add($myParam)
}
$arr = FillObject -array $arr -myParam "something"
$arr.Count
[System.Collections.Generic.List[String]]$lst = (New-Object System.Collections.Generic.List[String]])
function FillObject([System.Collections.Generic.List[String]][ref]$list,[String] $myParam) {
$list.Add($myParam)
}
FillObject -list ([ref]$lst) -myParam "something"
$lst.Count
你必须添加[ref]
无论是在功能定义,当你传递参数。如果这会帮助你 - PowerShell和C#依赖于.NET,因此它们的语法是类似的。 C#的方式来使用ref
:
int number = 1;
void Method(ref int refArgument)
{
refArgument = refArgument + 44;
}
Method(ref number);