【发布时间】:2018-08-05 19:12:39
【问题描述】:
引用数组
工作正常!
在 PowerShell 中通过引用传递数组的正常方法似乎工作正常:
Function Swap-Array ($theArray, $theArrayB, [int]$indexToSwap) {
$temp = $theArrayA[$indexToSwap];
$theArrayA[$indexToSwap] = $theArrayB[$indexToSwap];
$theArrayB[$indexToSwap] = $temp;
}
$a = @(1,2,3,4)
$b = @(3,2,4,1)
$a
$b
Swap-Array $a, $b, 2
$a
$b
输出:
a
-
1
2
3
4
b
-
3
2
4
1
a
-
1
2
4
3
b
-
3
2
3
1
问题
添加对象
当引用数组是一个非静态的 PSObjects 容器,并且我正在尝试添加新记录时,就会出现问题。修改现有记录好像没问题!
Function Swap-Apples($objectA, $objectB, $indexToSwap) {
$temp = $objectA[$indexToSwap].Apples;
$objectA[$indexToSwap].Apples = $objectB[$indexToSwap].Apples;
$objectB[$indexToSwap].Apples = $temp;
}
Function Swap-Oranges($objectA, $objectB, $indexToSwap) {
$temp = $objectA[$indexToSwap].Oranges;
$objectA[$indexToSwap].Oranges = $objectB[$indexToSwap].Oranges;
$objectB[$indexToSwap].Oranges = $temp;
}
<# heres the problematic bit #>
Function Add-Fruit ($object, [int]$howManyApples, [int]$howManyOranges) {
$hAdd = @{
Apples=$howManyApples
Oranges=$howManyOranges
}
$hToAdd = New-Object -TypeName PSObject -Property $hAdd;
$object += $hToAdd;
}
$a = @();
$b = @();
$a1 = @{
Apples=3
Oranges=2
}
$b1 = @{
Apples=5
Oranges=7
}
$a2 = @{
Apples=6
Oranges=3
}
$b2 = @{
Apples=1
Oranges=5
}
$aObject1 = New-Object -TypeName PSObject -Property $a1;
$bObject1 = New-Object -TypeName PSObject -Property $b1;
$aObject2 = New-Object -TypeName PSObject -Property $a2;
$bObject2 = New-Object -TypeName PSObject -Property $b2;
$a += $aObject1; $a += $aObject2;
$b += $bObject1; $b += $aObject2;
Write-Host "Values of A";
$a | Format-List
Write-Host "Values of B";
$b | Format-List
Write-Host "Now lets make a trade`!";
Swap-Apples $a $b 0
Swap-Oranges $a $b 1
Write-Host "Values of A";
$a | Format-List
Write-Host "Values of B";
$b | Format-List
Write-Host "Hey, I brought more fruit for A`!";
Add-Fruit -object $a -howManyApples 5 -howManyOranges 2
Write-Host "Values of A";
$a | Format-List
Write-Host "I brought more fruit for B too`!";
Add-Fruit -object $b -howManyApples 5 -howManyOranges 3
Write-Host "Values of B";
$b | Format-List
输出
Values of A
Oranges : 2
Apples : 3
Oranges : 3
Apples : 6
Values of B
Oranges : 7
Apples : 5
Oranges : 3
Apples : 6
Now lets make a trade!
Values of A
Oranges : 2
Apples : 5
Oranges : 3
Apples : 6
Values of B
Oranges : 7
Apples : 3
Oranges : 3
Apples : 6
Hey, I brought more fruit for A!
Values of A
Oranges : 2
Apples : 5
Oranges : 3
Apples : 6
I brought more fruit for B too!
Values of B
Oranges : 7
Apples : 3
Oranges : 3
Apples : 6
Swap-Apples 和 Swap-Oranges 函数似乎工作正常。该程序在最后一段崩溃了,试图给 A 和 B 更多的果实!否则这通常会在本地范围内工作。我觉得这由于引用传递而分崩离析。
我将如何解决这个程序结束时的问题?
【问题讨论】:
-
这不是错误。当您尝试将另一个项目添加到固定大小的数组时,会创建一个新数组
-
我所说的错误是指“修复它”。抱歉,如果我的上下文有点错误,呵呵。如何声明一个可以更改大小并通过引用传递的数组?
标签: arrays powershell pass-by-reference psobject