如何将ArrayList传递给函数并在Powershell中获取结果

时间:2019-02-04 08:08:17

标签: powershell arraylist

我试图将数组传递给函数并填充它,然后在函数外部打印结果。
但是第一个函数无法识别我传递给它的数组列表对象。

主文件:

. $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
    }
}

我做错了什么?
如何在function2和其他内部函数中使用相同的ArrayList?

1 个答案:

答案 0 :(得分:1)

如果要传递变量并在函数中对其进行修改并使用结果,则有两种方法:

按值传递:

$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

Pass by reference(您问的内容)

[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,则它们的语法相似。使用ref的C#方法:

int number = 1;
void Method(ref int refArgument)
{
    refArgument = refArgument + 44;
}
Method(ref number);