如何ArrayList的传递函数和PowerShell中得到返回结果

问题描述 投票:0回答:1

我想一个数组传递给函数并填写,然后打印功能之外的结果。 但第一函数不能识别数组列表对象我传递给它。

主文件:

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

powershell arraylist
1个回答
1
投票

如果你想传递一个变量并修改它在功能和使用效果有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

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,因此它们的语法是类似的。 C#的方式来使用ref

int number = 1;
void Method(ref int refArgument)
{
    refArgument = refArgument + 44;
}
Method(ref number);
© www.soinside.com 2019 - 2024. All rights reserved.