问题
I'm trying to make a simple swap function in PowerShell, but passing by reference doesn't seem to work for me.
function swap ([ref]$object1, [ref]$object2){
$tmp = $object1.value
$object1.value = $object2.value
$object2.value = $tmp
}
$a = 1
$b = 2
$a, $b
swap ([ref]$a) ,([ref]$b)
$a, $b
This SHOULD work, but no...
Output:
1
2
1
2
What did I do wrong?
回答1:
Call like this:
swap ([ref]$a) ([ref]$b)
The mistake of using , is described in the Common Gotchas for PowerShell here on Stack Overflow.
回答2:
By the way, PowerShell has a special syntax to swap values, and there isn't a need to use $tmp:
$a,$b = $b,$a
回答3:
Firstly, you're calling it wrong. Putting a comma in the call to swap means you're passing an array of them to objects as the first parameter. If you were to correct it...
swap ([ref]$a) ([ref]$b)
...it would then work.
来源:https://stackoverflow.com/questions/7149783/powershell-pass-by-reference-not-working-for-me