PowerShell pass by reference not working for me

▼魔方 西西 提交于 2019-11-29 16:46:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!